Can't set hidden input field's value using jQuery

前端 未结 11 1736
耶瑟儿~
耶瑟儿~ 2020-12-29 02:45

I have a simple input field inside a form tag:


  
相关标签:
11条回答
  • 2020-12-29 03:04

    Can you retrieve the value from the hidden field if you set the val tag?

    e.g.

    <input type="hidden" id="foo" name="foo" value="bar" />
    
    $(document).ready(function(){
      alert($('#foo').val());
    })
    
    0 讨论(0)
  • 2020-12-29 03:05

    I've confirmed that setting the value of a hidden field does not work with a jQuery selector like this...

    $('[name="my_field"]').val('Something');
    

    Will not update a hidden field... kinda shocking.

    <input type="hidden" name="my_field" id="my_field">
    

    Was forced to use a CSS hidden field instead.

    <input type="text" name="my_field" id="my_field" style="display:none">
    

    Apparently there are other issues with using the id of a hidden field as well... Set value of hidden field in a form using jQuery's ".val()" doesn't work

    Note: be sure to obtain the value in the console and not by inspecting.

    $('[name="my_field"]').val();
    
    0 讨论(0)
  • 2020-12-29 03:08

    I've had this problem when POST-ing my form and my PHP script couldn't get POST-ed value. I used this:

    $('#elemId').attr("name", theValue);
    

    Hope it helps.

    0 讨论(0)
  • 2020-12-29 03:09

    I had the same problem with a hidden input field. Id i set the initial value on 0, it works fine, but sometimes i didn't want to have an initial value of 0. So i tested with value=" ", a whitespace, and it works for me too. If you fill the value dynamic from PHP you could do value="<?= $val+0; ?>" if 0 is fine for you, or value="<?= $val; ?> " if a whitespace is fine.

    0 讨论(0)
  • 2020-12-29 03:11

    Rather then initialising your value attribute with an string initialise your input like this.

    <input type="hidden" name="foo" id="foo" value="${foo}">
    

    "foo" will contain the new value you set it too.

    0 讨论(0)
提交回复
热议问题