vektor vektor - 5 months ago 13
Javascript Question

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.

Answer

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