jQuery .val() not working for input fields

2019-04-18 16:36发布

问题:

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:

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

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.

回答1:

I have figured it out.

I was missing the name attribute on my input fields and for some reason .val() needed that to work.



回答2:

"According to W3C recommendations, 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!



回答3:

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