ChatGPT解决这个技术问题 Extra ChatGPT

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?


A
Andy E

: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, 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: 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: jsbin.com/elovo/2/edit
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: no problem. I would suggest using a proper debugging tool, Firebug 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.
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.
C
Chuck Callebs

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.


Beware, this can be very slow in older browsers (learn.jquery.com/using-jquery-core/selecting-elements)
Not working for me , browser - Chrome 48. Not sure why
z
zamber

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.


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).
That's why I posted this answer ;). Glad it helped. As for jQuery they have a potential fix here github.com/jquery/jquery/blob/… 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...
jQuery solution didn't worked for me either. Had to go with Vanilla JS.
B
Bo Persson

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"


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


S
Sophie

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


That's the answer I like. Using the attr function avoids all the contortions mentioned above and does the right thing.
佚名

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?
J
Jardalu

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.


S
Shawn

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

J
Julian Mann

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

W
WizardsOfWor

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.


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. In HTML5 the id may be any string that is not empty and does not contain any space characters (reference).
A
Arman H

Using ID:

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

Using class:

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

Y
Yarrabhumi

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

g
gillytech

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.


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


m
mzonerz

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

The OP is asking why the code like yours doesn't work for him, so this is useless for this question.
J
Joyrex

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.


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now