I have two form like this:

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

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!');

那么,如何只 Select 特定的表单元素呢?

推荐答案

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

您可以try :

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

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

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相关问答推荐

ASP.NET Core 8 MVC:从jQuery发布控制器中的所有值为空

如果在视窗中有相同的数据属性值,则jQuery/添加类

jQuery获取DOM node ?

如何使用 jQuery 获取所有 ID?

如何在 jQuery Select 器中定义 css :hover 状态?

如何使用 jQuery 重置 Select 元素

jQuery 滚动到 Div

是否可以使用 javascript 打开一个弹出窗口,然后检测用户何时关闭它?

在网络浏览器中,onblur 和 onfocusout 有什么区别?

jQuery.parseJSON 与 JSON.parse

JavaScript / jQuery:测试窗口是否有焦点

如何在 jQuery 中修改序列化的表单数据?

如何使用 jQuery 更改文本

更改占位符文本

jQuery、复选框和 .is(":checked")

jQuery vs jQuery Mobile vs jQuery UI?

Bootstrap datepicker Select 后隐藏

jQuery clone() 不克隆事件绑定,即使使用 on()

为什么我应该创建异步 WebAPI 操作而不是同步操作?

使用 Ajax 下载并打开 PDF 文件