开发者

Jquery change hidden form field value

I have this code but it isn't working on my localhost and I don't know why. Can anyone shed any light on this?

(Script is in head and the other code is in the body)

<script type="text/javascript">
$(function(){
 $(input[name='jsenabled']).val('1');

});
</script>



 <input type="hidden" name="jsenabled" value="0" />
    <label for="signup-email">Sign up for email offers, news &amp; events:</label>
    <input type="text" name="signup-email" id="signup-email" />
    <input type="submit" id="signup-button" value="Sign Me Up!" />
    <p id="signup-response"></p>
</fieldse开发者_StackOverflow社区t>

EDITED Weird thing is I have added this code to test if the value has been changed and it does fire up an alert, but firebug doesn't register the change.

$("input[name='jsenabled']").val("1");
    if($("input[name='jsenabled']").val = '1') {
    alert('frf');
    }


  1. jQuery selectors are strings: they must be quoted

  2. jQuery.val() is a method, not a property. Don't forget the parenthesis.

  3. The comparison operator is == not =.

You basically need to be more careful with your syntax.


You need quotes around the selector, like this:

$(function(){ 
  $("input[name='jsenabled']").val('1'); 
});

Also when checking the value, use parenthesis, like this:

if($("input[name='jsenabled']").val() == '1') {
  alert('frf');
}

.val() is a function, and called without any arguments gets the value.

On a more broad note, pay attention to the console, as Firebug should be throwing your JavaScript errors here for each of these, the console (which shows errors) is your best resource here.


Try $("input[name='jsenabled']").val('1'); Pay attention at double quotes I added.

edit See more issues in Nick's and Alvaro's answers.


Can u try this $('input[name="jsenabled"]').val('1');


Álvaro is generally right, but even with the right syntax you wouldn't be able to change the value of hidden fields, though jQuery sees them as readonly, if I recognize right.

I'd met this problem for myself a few weeks ago, my solution was a normal input with the css class 'hidden'

.hidden {
  display: none;
}

afterwards, you could simply change the value of the hidden input field:

jQuery('#field_id.hidden').val('new_field_value');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜