0

我有一个表格:

<form id="userForm" action="xpto">
     <input type="text" name="form[data_nascimento_beneficiario_1]" value />
     <input type="submit" value="Continuar" />
</form>

现在在一个脚本文件上,我尝试获取字段的长度以进行验证:

$("#userForm").submit(function (e) {
     alert($("input[name="form[data_nascimento_beneficiario_1]"]).length());
});

但我总是得到“TypeError:无法调用null的方法'length'”,

我想问题出在名称上有“form []”,但这是我无法改变的:(

任何人都可以帮助我吗?

向所有人致敬。

4

4 回答 4

3

那里有几个问题:

  1. 您引用的代码实际上存在语法错误,因此不会给您所说的错误,您已经在 word 之后结束了 JavaScript 字符串name

  2. 当您测试的属性值包含除字母 AZ 以外的任何内容时,最好将其放在引号中。

  3. length最后是“th”,而不是“ht”

  4. ...在 jQuery 中,它是一个属性,而不是一个方法,所以你不想要()

  5. 您在选择器 ( data_nascimento_baneficiario_1) 中使用的名称与表单 ( ) 中的名称不匹配data_nascimento_beneficiario_1,请注意选择器中“baneficirio”开头的“a”。

一起:活生生的例子| 来源

alert($('input[name="form[data_nascimento_beneficiario_1]"]').length);

(在那里,我习惯'在选择器字符串周围"加上引号,并在属性值周围加上引号。反之亦然。)

于 2013-10-07T13:46:09.163 回答
0

你有一个错字:.lenght()- 它应该是length. 另外,请注意您的报价包装。

将您的行更改为:

alert($("input[name='form[data_nascimento_baneficiario_1]']).length);
于 2013-10-07T13:46:06.303 回答
0

你有一个错字,长度不是一个函数(),所以不需要用()调用它

改变这个

lenght()

length

演示

于 2013-10-07T13:46:13.710 回答
0

请注意为什么这不起作用,但解决方法是

$("input").filter(function(){ 
     return this.name = 'form[data_nascimento_beneficiario_1]'}
).val().length
于 2013-10-07T13:47:13.117 回答