Set value of hidden field in a form using jQuery's ".val()" doesn't work

JquerySetHidden Fields

Jquery Problem Overview


I've been trying to set the value of a hidden field in a form using jQuery, but without success.

Here is a sample code that explains the problem. If I keep the input type to "text", it works without any trouble. But, changing the input type to "hidden", doesn't work !

<html>
    
    <head>
        <script type="text/javascript" src="jquery.js">
        </script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("button").click(function() {
                    $("input:text#texens").val("tinkumaster");
                });
            });
        </script>
    </head>
    
    <body>
        <p>
            Name:
            <input type="hidden" id="texens" name="user" value="texens" />
        </p>
        <button>
            Change value for the text field
        </button>
    </body>

</html>

I also tried the following workaround, by setting the input type to "text" and then using a "display:none" style for the input box. But, this also fails ! It seems jQuery has some trouble setting hidden or invisible input fields.

Any ideas? Is there a workaround for this that actually works?

Jquery Solutions


Solution 1 - Jquery

:text will fail for a input with a type value of hidden. It's also much more efficient to just use:

$("#texens").val("tinkumaster");

ID attributes should be unique on a web page, make sure yours are as this may contribute to any problems you're having, and specifying a more complicated selector just slows things down and doesn't look as neat.

Example at http://jsbin.com/elovo/edit, using your example code at http://jsbin.com/elovo/2/edit

Solution 2 - Jquery

If you're having trouble setting the value of a hidden field because you're passing an ID to it, this is the solution:

Instead of $("#hidden_field_id").val(id) just do $("input[id=hidden_field_id]").val(id). Not sure what the difference is, but it works.

Solution 3 - Jquery

Finally, I have found a solution and it's a simple one:

document.getElementById("texens").value = "tinkumaster";

Works like a charm. No clue why jQuery does not fall back to this.

Solution 4 - Jquery

I had same problem. oddly enough google chrome and possibly others (not sure) did not like

$("#thing").val(0);

input type="hidden" id="thing" name="thing" value="1" />

(no change)

$("#thing").val("0");

input type="hidden" id="thing" name="thing" value="1" />

(no change)

but this works!!!!

$("#thing").val("no");

input type="hidden" id="thing" name="thing" value="no" />

CHANGES!!

$("#thing").val("yes");

input type="hidden" id="thing" name="thing" value="yes" />

CHANGES!!

must be a "string thing"

Solution 5 - Jquery

$('input[name=hidden_field_name]').val('newVal');

worked for me, when neither

$('input[id=hidden_field_id]').val('newVal');

nor

$('#hidden_field_id').val('newVal');

did.

Solution 6 - Jquery

.val didnt work for me, because i'm grabbing the value attribute server side and the value wasn't always updated. so i used :

var counter = 0;
$('a.myClickableLink').click(function(event){
   event.preventDefault();
   counter++;
 
   ...
   $('#myInput').attr('value', counter);
}

Hope it helps someone.

Solution 7 - Jquery

Actually, this is an ongoing problem. While Andy is right about the downloaded source, .val(...) and .attr('value',...) don't seem to actually modify the html. I think this is a javascript problem and not a jquery problem. If you had used firebug even you would have had the same question. While it seems that if you submit the form with the modified values it will go through, the html does not change. I ran into this issue trying to create a print preview of the modified form (doing [form].html()) it copies everything okay, including all changes except values changes. Thus, my modal print preview is somewhat useless... my workaround may have to be to 'build' a hidden form containing the values they have added, or generate the preview independently and make each modification the user makes also modify the preview. Both are inoptimal, but unless someone figures out why the value-setting behavior does not change the html (in the DOM i'm assuming) it will have to do.

Solution 8 - Jquery

I was having the same issue, and I found out what was wrong. I had the HTML defined as

<form action="url" method="post">
    <input type="hidden" id="email" />
<form>
<script>
    function onsomeevent()
    {
       $("#email").val("[email protected]");
    }
</script>

Reading the form values on server always resulted in email as empty. After scratching my head (and numerous search), I realized the mistake was not defining the form/input correctly. On modifing the input (as shown next), it worked like a charm

<input type="hidden" id="email" name="email" />

Adding to this thread in case others have the same issue.

Solution 9 - Jquery

In my case, I was using a non-string (integer) as the parameter of val() which doesn't work, the trick is just as simple as

$("#price").val('' + price);

Solution 10 - Jquery

Using val() didn't work for me. I had to use .attr() everywhere. Also I had different types of inputs and had to be pretty explicit in the case of check boxes and select menus.

Update textfield

$('#model_name').attr('value',nameVal);

Update image next to file input

$('#img-avatar').attr('src', avatarThumbUrl);

Update boolean

if (isActive) {
    $('#model_active').attr('checked',"checked");
} else {
    $('#model_active').attr('checked', null) ;
}

Update select (with number or string)

$('#model_framerate').children().each(function(i, el){
    var v = $(el).val();
    if (v === String(framerateVal)) { 
        $(el).attr('selected','selected');
    } else {
        $(el).attr('selected',null);
    }
}

Solution 11 - Jquery

Another gotcha here wasted some of my time, so I thought I would pass along the tip. I had a hidden field I gave an id that had . and [] brackets in the name (due to use with struts2) and the selector $("#model.thefield[0]") would not find my hidden field. Renaming the id to not use the periods and brackets caused the selector to begin working. So in the end I ended up with an id of model_the_field_0 instead and the selector worked fine.

Solution 12 - Jquery

Using ID:

$('input:hidden#texens').val('tinkumaster');

Using class:

$('input:hidden.many_texens').val('tinkumaster');

Solution 13 - Jquery

If you are searching for haml then this is the answer for hidden field to set value to a hidden field like

%input#forum_id.hidden

In your jquery just convert the value to string and then append it using attr property in jquery. hope this also works in other languages also.

$('#forum_id').attr('val',forum_id.toString());

Solution 14 - Jquery

After getting lost in the myriad answers on this page, none of which actually worked, I found out how to do this in my case.

For some reason using input in the selector was not doing it. I did not have an ID on the form element so I couldn't use any IDs for selectors. And even if I did I'm pretty sure it wouldn't have worked.

Here's my solution:

$("[name=something]").val("something");

Essentially, select any element with the name of "something". Give it a shot.

Solution 15 - Jquery

<javascript>


slots=''; hidden=''; basket = 0;
	
	cost_per_slot = $("#cost_per_slot").val();
	//cost_per_slot = parseFloat(cost_per_slot).toFixed(2)

	for (i=0; i< check_array.length; i++) {
		slots += check_array[i] + '\r\n';
		hidden += check_array[i].substring(0, 8) + '|';
		basket = (basket + parseFloat(cost_per_slot));
	}
	
	// Populate the Selected Slots section
	$("#selected_slots").html(slots);
	
	// Update hidden slots_booked form element with booked slots
	$("#slots_booked").val(hidden);		

	// Update basket total box
	basket = basket.toFixed(2);
	$("#total").html(basket);

Solution 16 - Jquery

Simply use syntax below get and set

GET

//Script 
var a = $("#selectIndex").val();

here a variable will hold the value of hiddenfield(selectindex)

Server side

<asp:HiddenField ID="selectIndex" runat="server" Value="0" />

SET

var a =10;
$("#selectIndex").val(a);

Solution 17 - Jquery

Anyone else who is struggling with this, there is a very simple "inline" way to do this with jQuery:

<input type="search" placeholder="Search" value="" maxlength="256" id="q" name="q" style="width: 300px;" onChange="$('#ADSearch').attr('value', $('#q').attr('value'))"><input type="hidden" name="ADSearch" id="ADSearch" value="">

This sets the value of the hidden field as text is typed into the visible input using the onChange event. Helpful (like in my case) where you want to pass on a field value to an "Advanced Search" form and not force the user to re-type their search query.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontexensView Question on Stackoverflow
Solution 1 - JqueryAndy EView Answer on Stackoverflow
Solution 2 - JqueryChuck CallebsView Answer on Stackoverflow
Solution 3 - JqueryzamberView Answer on Stackoverflow
Solution 4 - Jquerymr.zagaView Answer on Stackoverflow
Solution 5 - JqueryDirk SeifertView Answer on Stackoverflow
Solution 6 - JquerySophieView Answer on Stackoverflow
Solution 7 - Jqueryuser444777View Answer on Stackoverflow
Solution 8 - JqueryJardaluView Answer on Stackoverflow
Solution 9 - JqueryShawnView Answer on Stackoverflow
Solution 10 - JqueryJulian MannView Answer on Stackoverflow
Solution 11 - JqueryWizardsOfWorView Answer on Stackoverflow
Solution 12 - JqueryArman HView Answer on Stackoverflow
Solution 13 - JqueryYarrabhumiView Answer on Stackoverflow
Solution 14 - JquerygillytechView Answer on Stackoverflow
Solution 15 - JquerycarolinaView Answer on Stackoverflow
Solution 16 - JquerymzonerzView Answer on Stackoverflow
Solution 17 - JqueryJoyrexView Answer on Stackoverflow