195

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?

xr280xr
  • 10,471
  • 6
  • 68
  • 110
texens
  • 3,277
  • 3
  • 19
  • 21

16 Answers16

329

: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

Andy E
  • 311,406
  • 78
  • 462
  • 440
  • Andy, thanks for the quick response. I actually tried with the "#texens" first, and then with "#input:hidden#texens" and neither of them seemed to work. When I changed the input type in the form from "hidden" to "text", and "#input:hidden:texens" to "#input:text:texens", it worked without any trouble. The "#input:text#texens" was a typo above, and should have been "#input:hidden#texens" or just "#texens" as you have just mentioned. So, it seems that the hidden field's values are not being changed. – texens Jun 05 '10 at 10:06
  • 1
    @texens: I would suspect the problem lies elsewhere. As you can see from the example I linked to, `val()` works just fine on the hidden input, changing the value from "not changed" to "changed". I've revised the example to include the code you pasted above, with an alert to confirm the value change: http://jsbin.com/elovo/2/edit – Andy E Jun 05 '10 at 10:18
  • Andy, Thanks a lot for the example. I ran the code mentioned above and it works exactly as it is supposed to be. And the alert indeed confirms that the value has been changed. I had been opening up the page source using Firefox's "View Page Source" feature. And in the page source, it still shows the old value and not the new value (even for the code in the pastebin mentioned above). But, the alert box confirms the changed value. So, I'm assuming this is a Firefox problem (or am I being too stupid and overlooking something important?). Once again, thanks for your time :) – texens Jun 05 '10 at 10:25
  • 2
    @texens: no problem. I would suggest using a proper debugging tool, [Firebug](http://getfirebug.com) if you use Firefox, instead of viewing source. The behaviour of "view source" is more or less the same across all browsers, and will show the downloaded, unmodified source code of the page. – Andy E Jun 05 '10 at 10:34
  • 2
    I don't think the issue is with Firefox or a specific tool as much as it is with how modified HTML is rendered and displayed. I have the same situation as the OP, except that there is quite a bit more jQuery involved. In my case, as in this one, the code works correctly - the click event correctly updates an input of type "hidden' - but Firebug does not display the updated values for hidden fields, even though they have been updated and jQuery can access them, and even though updated values for visible fields are displayed in Firebug correctly. – Dave DuPlantis Apr 27 '11 at 17:50
  • Firebug updates values just fine, you may have an issue elsewhere Dave DuPlantis. – Ed DeGagne Nov 12 '13 at 15:30
  • What about to set hidden field value using jquery and pass to controller on form submission and access that same value set at controller side? – 3 rules Dec 21 '16 at 13:00
64

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.

Chuck Callebs
  • 15,625
  • 8
  • 53
  • 71
27

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.

zamber
  • 900
  • 8
  • 22
  • Technically this uses the DOM not jQuery, but it is simple, and works (I tried nearly every answer on here for my case of changing the value at form submission time, and they weren't working). – hlongmore Jul 02 '18 at 20:57
  • That's why I posted this answer ;). Glad it helped. As for jQuery they have a potential fix here https://github.com/jquery/jquery/blob/ac9e3016645078e1e42120822cfb2076151c8cbe/src/attributes/attr.js#L79 but it's only for `type="radio"`. I'm to lazy to report an issue, especially given I solved this problem 4 years ago. I'm also torn if it should be fixed in jQuery - possibly it's implemented that way to protect jQuery kiddies from themselves? Who knows... – zamber Jul 04 '18 at 21:32
  • 1
    jQuery solution didn't worked for me either. Had to go with Vanilla JS. – Varun Sharma Feb 27 '20 at 10:09
17

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"

Bo Persson
  • 86,087
  • 31
  • 138
  • 198
mr.zaga
  • 179
  • 1
  • 2
  • 2
    This fixed it for me as well. I ended up using `.val(' 0')`, which is correctly parsed by `parseInt` in Javascript as well as `int()` in Python, my backend. – rattray Feb 26 '14 at 23:32
11
$('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.

Dirk Seifert
  • 111
  • 1
  • 5
10

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

Sophie
  • 229
  • 3
  • 10
  • That's the answer I like. Using the attr function avoids all the contortions mentioned above and does the right thing. –  Jul 30 '14 at 00:24
7

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.

  • +1 from me ! You're right. value and .val() has having problem while updating it using jQuery. Did you found anything around? – NullPointer Jul 23 '13 at 09:00
4

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("a@a.com");
    }
</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.

Jardalu
  • 201
  • 2
  • 9
3

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);
Shawn
  • 1,398
  • 1
  • 11
  • 17
2

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);
    }
}
Julian Mann
  • 5,377
  • 4
  • 27
  • 41
1

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.

WizardsOfWor
  • 2,416
  • 25
  • 20
  • That's because your selector `$("#model.thefield[0]")` is being interpreted as: an element with `id` equal to `model`, a css `class` of `thefield` and some `attribute` called `0`... If you want to use those characters in your `id` use the approach suggested by Chuck Callebs in [his answer](http://stackoverflow.com/a/8073145/177710). In HTML5 the `id` may be any string that is not empty and does not contain any space characters ([reference](http://www.w3.org/TR/html-markup/global-attributes.html#common.attrs.id)). – Oliver Apr 25 '13 at 09:05
1

Using ID:

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

Using class:

$('input:hidden.many_texens').val('tinkumaster');
Arman H
  • 5,018
  • 9
  • 47
  • 70
0

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());
Yarrabhumi
  • 18
  • 5
-1
<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);

-1

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);
mzonerz
  • 1,070
  • 11
  • 19
  • 1
    The OP is asking why the code like yours doesn't work for him, so this is useless for this question. – ProfK Dec 03 '19 at 12:34
-1

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.

Joyrex
  • 1,063
  • 14
  • 24