jQuery .val()不适用于输入字段 [英] jQuery .val() not working for input fields

查看:82
本文介绍了jQuery .val()不适用于输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获我的输入字段的值,并在表单类中使用以下方法来做到这一点:

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]);
    });
},

(不要介意选择"字段,这是一个自定义的选择框,我将不得不用不同的方式来处理) 我在表单更改事件上执行捕获. 输入字段都具有正确的ID,它们看起来像这样:

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

我还将注意到,该表单正在使用Ajax加载,但是由于它通常捕获字段上的change事件,因此我怀疑这是问题所在.

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.

推荐答案

我已经弄清楚了.

我在输入字段上缺少名称属性,由于某种原因,.val()需要它才能起作用.

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

这篇关于jQuery .val()不适用于输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆