javascript jQuery val 函数不适用于隐藏字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19704017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:33:01  来源:igfitidea点击:

jQuery val function not working on a hidden field?

javascriptphpjquery

提问by Renish Khunt

This is my HTMLcode:

这是我的HTML代码:

<div style='display:none;' id='allformid'>
    <div>
        <form action='#'>
              <input type='text' name='name' id='named'/>
        </form>
    </div>
</div>

And this is my jQuerycode to set the value of the input text box:

这是我jQuery设置输入文本框值的代码:

$("#allformid  #named").val('abcd');

This jQuerycode is correct, but the form value is not changed.

这段jQuery代码是正确的,但表单值没有改变。

回答by Neville Nazerane

I tried the same code it works fine. How did you test that the code works or not?

我尝试了相同的代码,它工作正常。你是如何测试代码是否有效的?

If you check the inspect element, it will not show value="abcd". But if you make the div visible, you can see the value is given. But the value gets set. You can also test the value by getting the value in the js console like this:

如果您检查检查元素,它不会显示 value="abcd"。但是如果你让 div 可见,你可以看到给出的值。但该值已设置。您还可以通过在 js 控制台中获取值来测试该值,如下所示:

$("#allformid #named").val();

$("#allformid #named").val();

However if you want it to display as value="abcd", you will need to write $("#allformid #named").attr("value",'abcd');

但是,如果您希望它显示为 value="abcd",则需要编写 $("#allformid #named").attr("value",'abcd');

回答by Rajnikant Kakadiya

html

html

<form action='#'>
      <input type='hidden' value='' name='name' id='named'/>
</form>

jQuery

jQuery

$("#named").val('abcd');