Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find elements where name is different than id using jQuery

Tags:

jquery

How do I write jQuery expression that will find inputs where the name attribute value is different from the id attribute value?

This should be found

<input name="foo" id="bar" />

This should not be found

<input name="foo" id="foo" />

Trivial stuff like $('input[name!=id]') fails, because the [] expression expects a constant on the right hand side.

like image 282
vektor Avatar asked Aug 17 '15 13:08

vektor


People also ask

How do you find the value of an element with a name instead of ID?

Just type the name of the element without "<" and ">" characters. For example type P, not <P> if the answer is the <P> element. Save this answer.

Does jQuery use id or name?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I find an element with a specific ID?

Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

How do you target an element ID in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.


1 Answers

You can do this using filter() function. And use trim to make sure.

Edit Simple version

$('input').filter(function(){
    return this.id != this.name;
});

If there are any issues because of trailing or leading spaces, then the following can be used.

$('input').filter(function(){
    thisID = $.trim(this.id);
    thisName =  $.trim(this.name);
    return thisID != thisName;
});
like image 54
rrk Avatar answered Sep 23 '22 13:09

rrk