如何在jQuery中选择特定的表单元素? [英] How to select specific form element in jQuery?

查看:62
本文介绍了如何在jQuery中选择特定的表单元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种这样的形式:

<form id='form1' name='form1'>
  <input name='name' id='name'>
  <input name='name2' id='name2'>
</form>

<form id='form2' name='form2'>
  <input name='name' id='name'>
  <input name='name2' id='name2'>
</form>

现在,我想在 form2 名称字段中插入文本.我正在使用遵循jQuery代码,但它会填充 form1 .

Now I want to insert text in name field of form2. I am using following jQuery code but it fill name field of form1.

$("#name").val('Hello World!');

那么如何只选择特定的表单元素?

So how to select specific form elements only?

推荐答案

两次具有相同的ID是无效的,这就是#name只找到第一个ID的原因.

It isn't valid to have the same ID twice, that's why #name only finds the first one.

您可以尝试:

$("#form2 input").val('Hello World!');

或者,

$("#form2 input[name=name]").val('Hello World!');

如果您停留在无效页面上并想要选择所有#name,则可以在id上使用属性选择器:

If you're stuck with an invalid page and want to select all #names, you can use the attribute selector on the id:

$("input[id=name]").val('Hello World!');

这篇关于如何在jQuery中选择特定的表单元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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