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

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?

This question is related to jquery set hidden-fields

The answer is


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.


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());

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);
    }
}

Using ID:

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

Using class:

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

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.


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);

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);

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.


.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.


$('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.


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.


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.


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.


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"


<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);