jQuery选择器按表单索引和输入名称

jQuery selector by form index and input name

本文关键字:输入 索引 选择器 表单 jQuery      更新时间:2023-09-26

下面的页面有两个不同类的表单,但每个表单都有一个相同名称的输入。

<form class='first_form'>
 <input name='test' value='1' />
</form>
<form class='second_form'>
 <input name='test' value='3'/>
</form>

我可以得到表单索引,我知道输入的名称,但我不知道输入的索引。

有没有一种方法可以将选择器与表单索引和输入名称链接以获得值?

我试过链接,但似乎什么都不起作用

var inputName = 'test';
Var formIndex = 1;
$('*[name="' + inputName + '"]' +' ' + '$("form").eq(' + formIndex + ')').val();

FIDDLE

var formIndex=0;
var inputName="txtbox";
vall= $("form:eq("+ formIndex+") input[name= "+ inputName +" ]").val();
alert(vall);

您的订单是错误的

您可以使用以下任一项直接在DOM中访问表单的元素:

document.forms[formIndex]
document.forms[formName]

然后,您可以通过name使用引用输入元素

document.forms[formIndex][inputName]
document.forms[formName][inputName]

然后,只需将其包装在$(...)中,即可获得一个jQuery集合。在您的情况下:

var inputName = 'test',
    formIndex = 1;
$(document.forms[formIndex][inputName]);

我想这是迄今为止最具表演性的方式,也是可读的。

为了添加一些细节,document.forms是文档中所有HTMLFormElementHTMLCollection。给定任何HTMLCollectionHTMLFormElement,您都可以访问其中的命名元素作为属性。

未测试,但你能做到吗:

$('form:nth-of-type(1) input[name="test"]').val();
$("form:nth-child("+formIndex+") input[name='"+inputName+"']").val();

你可以用一种更聪明的方法:

var fieldName = 'test';
var formId = '.first_form'
$('form'+formId+' input[name='+fieldName+']).val()

不要使用索引,而是使用命名选择器,如id或class。它将帮助你在未来找到正确的形式(当你有5个以上时,很难计算出你正在看的女巫:)但这太复杂了:)

我建议这样做:

 var currentForm = $('form'+formId);
 currentForm//here you can put a log into console if element has not been found and find that bug sooner.
 currentForm.find('input[name='+fieldName+']').val()