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

So how to select specific form elements only?

推荐答案

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

You can try:

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

Or,

$("#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相关问答推荐

当父迪瓦是重复元素时,如何将一些子元素包裹在父迪瓦中

将div中的下一个2个标题分组

使用jQuery筛选器搜索输入仅适用于单词的一部分

如果链接包含多个关键字,jQuery 将 HTML 添加到链接

将元素附加到每个函数 jQuery

AngularJS 中的 ScrollTo 函数

JavaScript 或 jQuery 字符串以实用函数结尾

如何在 jquery 中从这个日期减go 一周?

如何在数据表中显示空数据消息

扩展 jQuery 插件的最佳方式

如何使用 jQuery 或 JavaScript 模拟单击​​按钮的动作?

lodash debounce 在匿名函数中不起作用

moment.js isValid 函数无法正常工作

如何在我的 WordPress 插件中包含 CSS 和 jQuery?

C# String.IsNullOrEmpty Javascript 等效项

如何在 JQuery 中 Select 除单击元素之外的所有类?

在 jQuery 中 Select 后代元素的最快方法是什么?

调整浏览器大小时如何自动居中 jQuery UI 对话框?

如何使用 jquery 使下拉列表只读?

清除表jquery