4

Is there any function to check if an input has a specific name in jquery, like we check the existense of a class using hasClass()?

For example if I have an input

<input type="checkbox" class="col_control" checked="checked" name="sr_column" data-columnno="0" />

so that I can check hasName("sr_column") and it returns true

3 Answers 3

22
el.name == 'text'

No need for any jQuery! If you do have a jQuery object, use jq_el[0].name == 'text' instead.

Of course you can also use jQuery to access this, using either jq_el.prop('name') or jq_el.attr('name') (it's available both as a property and an attribute).

If you want jq_el.hasName(...), you can define the function like this:

$.fn.hasName = function(name) {
    return this.name == name;
};
Sign up to request clarification or add additional context in comments.

Comments

4

Try this also

 var name = $("#id").attr("name");

OR

 var name = $("#id").prop("name");


if(name=="sr_column")
{
   //your code
}

1 Comment

Thanks for the answer. That's what I was doing already but the method didn't seem OK to me... So just a +1 for you :)
0

Just for completeness, one can also use $.filter() on the jQuery objects and check the length of the list, e.g.

var $inputs = $("input");
if ($inputs.filter("[name=text]").length > 0) {
    // do something here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.