Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Test to see if name attribute is equal to a given string

Tags:

jquery

Given a list of HTML inputs, textareas, and selects, I would like to check and see if any have a name attribute equal to a given string, and if any do, to add a class to it.

For example:

if($('textarea, input, select').attr("name") == "this_name"){
    $(this).addClass("myClass");
}

I'm just not sure what I', doing wrong here, but it doesn't seem to be working.

like image 331
kylex Avatar asked Jun 21 '11 15:06

kylex


3 Answers

try:

$("textarea[name='this_name'], input[name='this_name'], select[name='this_name']").addClass("myClass");

Look to use CSS3 selectors within jQuery

like image 70
Michael Wright Avatar answered Nov 04 '22 07:11

Michael Wright


What you are looking for is:

$('textarea, input, select').filter('[name="this_name"]').addClass("myClass");

because your .attr() will look for the nameattribute of the first matched element (see the documentation on attr)

like image 38
instanceof me Avatar answered Nov 04 '22 07:11

instanceof me


Something like:

$("textarea[name='this_name']").addClass("myClass");

See: http://api.jquery.com/attribute-equals-selector/

like image 31
cdm9002 Avatar answered Nov 04 '22 08:11

cdm9002