jQuery 如何通过名称而不是 ID 获取元素的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2109472/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:48:13  来源:igfitidea点击:

How to get a value of an element by name instead of ID

jquery

提问by Elitmiar

How could I get the value of a element by name instead of by ID eg if I use by id it would be $('#id').val();

我怎样才能通过名称而不是通过 ID 获取元素的值,例如,如果我通过 id 使用它将是 $('#id').val();

回答by Nick Craver

Use the name attribute selector:

使用名称属性选择器:

$("input[name=nameGoesHere]").val();

回答by rfunduk

$('[name=whatever]').val()

The jQuery documentationis your friend.

jQuery文档是您的朋友。

回答by vineel

Use the name attribute selector:

使用名称属性选择器:

$("input[name='nameGoesHere']").val();

It is a mandatory requirement to include quotes around the value, see: http://api.jquery.com/attribute-equals-selector/

在值周围包含引号是强制性要求,请参阅:http: //api.jquery.com/attribute-equals-selector/

回答by Anshul

To get the value, we can use multiple attributes, one of them being the nameattribute. E.g

要获取值,我们可以使用多个属性,其中之一是name属性。例如

$("input[name='nameOfElement']").val();

We can also use other attributes to get values

我们还可以使用其他属性来获取值

HTML

HTML

<input type="text" id="demoText" demo="textValue" />

JS

JS

$("[demo='textValue']").val();

回答by Ajay Kumar

This works fine .. here btnAddCat is button id

这工作正常..这里 btnAddCat 是按钮 id

$('#btnAddCat').click(function(){
        var eventCategory=$("input[name=txtCategory]").val();
        alert(eventCategory);
    });

回答by jones

//name directly given
<input type="text" name="MeetingDateFrom">
var meetingDateFrom = $("input[name=MeetingDateFrom]").val();

//Handle name array
<select multiple="multiple" name="Roles[]"></select>
 var selectedValues = $('select[name="Roles[]"] option:selected').map(function() {
    arr.push(this.value);
  });

回答by Amira Ahmed

What element is used for the part with a green background? Just type the name of the element without "<" and ">" characters. For example type P, not <P>if the answer is the <P>element.

绿色背景部分使用什么元素?只需键入不带“<”和“>”字符的元素名称。例如输入 P,<P>如果答案是<P>元素,则不输入。

回答by cyberoot

you can also use the class name.

你也可以使用类名。

$(".yourclass").val();

回答by Abnormal

let startDate = $('[name=daterangepicker_start]').val();
alert(startDate);