jQuery 如何在jQuery中选择特定的表单元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4387319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select specific form element in jQuery?
提问by Awan
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 namefield of form2. I am using following jQuery codebut it fill namefield of form1.
现在我想在form2 的name字段中插入文本。我正在使用以下 jQuery 代码,但它填充了form1 的名称字段。
$("#name").val('Hello World!');
So how to select specific form elements only?
那么如何只选择特定的表单元素呢?
回答by Kobi
It isn't valid to have the same ID twice, that's why #name
only finds the first one.
两次使用相同的 ID 是无效的,这就是为什么#name
只找到第一个。
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 #name
s, you can use the attribute selector on the id:
如果您遇到无效页面并想选择所有#name
s,则可以在 id 上使用属性选择器:
$("input[id=name]").val('Hello World!');
回答by tawfekov
although it is invalid html but you can use selector context to limit your selector in your case it would be like :
虽然它是无效的 html,但您可以使用选择器上下文来限制您的选择器在您的情况下它会像:
$("input[name='name']" , "#form2").val("Hello World! ");
$("input[name='name']" , "#form2").val("Hello World! ");
回答by Marcos Sedrez
I prefer an id descendant selector of your #form2, like this:
我更喜欢 #form2 的 id 后代选择器,如下所示:
$("#form2 #name").val("Hello World!");
回答by Adeel Raza Azeemi
I know the question is about setting a input but just in case if you want to set a combobox then (I search net for it and didn't find anything and this place seems a right place to guide others)
我知道问题是关于设置输入,但以防万一如果你想设置一个组合框(我在网上搜索它但没有找到任何东西,这个地方似乎是指导他人的正确地方)
If you had a form with ID attribute set (e.g. frm1) and you wanted to set a specific specific combobox, with no ID set but name attribute set (e.g. district); then use
如果您有一个设置了 ID 属性的表单(例如 frm1)并且您想设置一个特定的特定组合框,没有设置 ID 但设置了名称属性(例如区);然后使用
$("#frm1 select[name='district'] option[value='NWFP']").attr('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="frm1">
<select name="district">
<option value="" disabled="" selected="" hidden="">Area ...</option>
<option value="NWFP">NWFP</option>
<option value="FATA">FATA</option>
</select>
</form>
回答by bbbbb
$("#name", '#form2').val("Hello World")