1
<input name="Indian_Karnataka_Bangalore" value="Bangalore" />
<input name="Indian_Andhra_Hyderabad" value="Hyderabad" />
<input name="Indian_Kerala_Trivandrum" value="Trivandrum" />
<input name="Indian_Maharashtra_Mumbai" value="Mumbai" />

At a given time, only one input element will be present in the DOM. How will I know the name of the specific input element name? I don't want to depend on values as it might change. Using jQuery.

The INDIAN term will be static in every input element.

Actually i am trying to validate the input elements. DOM will have all the elements but at a given time only one element will be active and that element should have some value in it.

4

5 回答 5

2
var $inputs = $('input[name*="Indian"]'),
    inputsName = $inputs.attr('name');

您可以使用与 CSS 相同的选择器。

Chris Coyier 在这里写了一篇关于属性选择器的文章

于 2013-04-29T08:25:43.487 回答
1
var indianInputs = $("input[name^='Indian']"); 
//Matches all input elements whose name attrributes 'begin' with 'Indian'

这与@ahren 发布的不同之处在于,他的选择器将匹配 name 属性包含字符串“Indian”的所有输入元素。

indianInputs.attr("name");

将返回第一个匹配元素的名称属性值,对于您的标记,该值将是Indian_Karnataka_Bangalore

要查找 all 的名称indianInputs,您必须遍历所有匹配的元素

var indianInputNames = [];
indianInputs.each(function() {
    indianInputNames.push($(this).attr("name"));
});
于 2013-04-29T08:31:32.507 回答
0
 $('input[name="element_name"]')

You have a lot of ways to select by the name of the attribute check http://api.jquery.com/category/selectors/attribute-selectors/

于 2013-04-29T08:29:57.867 回答
0

Try

var name = $('input[name^="Indian_"]').attr('name')
于 2013-04-29T08:30:28.093 回答
0

你试过过滤功能吗?像这样的东西:

$('input:visible')
    .filter(function() {
        return $(this).attr("name").match(/^Indian/);
});

这将返回一个名称以“Indian”开头的输入元素数组。这里有一个很好的例子:https ://stackoverflow.com/a/193787/1237117 。

于 2013-04-29T08:33:10.503 回答