jQuery .val() 不适用于输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21407017/
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
jQuery .val() not working for input fields
提问by Nicolas
I'm trying to capture value of my input fields and have following method in my form class to do that:
我正在尝试捕获输入字段的值,并在我的表单类中使用以下方法来做到这一点:
getData: function() {
var fields = ['name', 'email', 'message'];
$.each(fields, function(index, el) {
form.data[el] = $('#'+el).val();
console.log(form.data[el]);
});
},
(nevermind the 'select' field, that's a custom made select box and I'll have to handle that one differently) I perform the capture on form change event. The input fields all have proper id's, they look something like this:
(不用管“选择”字段,这是一个定制的选择框,我必须以不同的方式处理它)我在表单更改事件上执行捕获。输入字段都有正确的 id,它们看起来像这样:
<input type="text" id="name">
<input type="email" id="email">
<textarea name="message" id="message"></textarea>
Now, when I type something in the fields I only get value from the textarea, while other inputs give me undefined.
现在,当我在字段中输入某些内容时,我只能从 textarea 获取值,而其他输入则给我未定义的值。
I'll also note that the form is being loaded with Ajax, but since it captures the change event on the fields normally I doubt that this is the problem.
我还会注意到表单正在使用 Ajax 加载,但由于它通常会捕获字段上的更改事件,因此我怀疑这是问题所在。
回答by Nicolas
I have figured it out.
我已经想通了。
I was missing the name attribute on my input fields and for some reason .val() needed that to work.
我在输入字段上缺少 name 属性,出于某种原因 .val() 需要它才能工作。
回答by Richard Bradley Smith
"According to W3Crecommendations, an html for can only send data if the input field has a control name. Ids do not count." Well, that is all fine and good (priceless, in fact) but jQuery .val()
would have one believe it can happily use the id=
as a selector if you look at this example. My testing showed not only does one have to have id=
and name=
but they have to be the same. I so love this stuff when it works!
“根据W3C 的建议,如果输入字段具有控件名称,则 html for 只能发送数据。ID 不计算在内。” 好吧,这一切都很好(实际上是无价的),但是如果您查看此示例,您jQuery .val()
会相信它可以愉快地将id=
用作选择器。我的测试表明,不仅必须拥有,而且必须相同。当它起作用时,我非常喜欢这些东西!id=
name=
回答by hoogw
No, You do not have to have both name and id attribute for val to work. I had test it, with only id , .val() works fine
不,您不必同时具有 name 和 id 属性才能使 val 工作。我已经测试过了,只有 id , .val() 工作正常