vektor
vektor

Reputation: 2926

Find elements where name is different than id using 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.

Upvotes: 11

Views: 832

Answers (1)

rrk
rrk

Reputation: 15846

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;
});

Upvotes: 18

Related Questions