jQuery selector comparing element's attributes

2019-03-05 22:21发布

问题:

The thing starts from my previous question: Using jQuery is it possible to compare two attributes in a selector? I mean something like:

$('element[atribute1!=attribute2]')

or, in a practical example:

$('input[name!=id]')

In my case, I would need it to get how many input fields haven't been changed in an html form used to edit something, I was trying to get this code to work:

if($('input[DefaultValue!=input.value]').lenght==0){...}

What about it? It should return the number of changed fields (if i get 0 i will stop form submission, show an alert message and go back without updating)

Thank for your help.

回答1:

No. If you look through jQuery's documentation, you'll see there's no such selector.

Also defaultValue is a property, not an attribute.

You can do this:

var changed = $('input').filter(function() {
    return this.value !== this.defaultValue;
});


回答2:

You can use the jQuery filter() function, like this:

var different = $('input').filter(function()
{
    return $(this).attr('data-default-value') != $(this).val();   
});

Then, you can test different.length > 0.

Here's a full working example: http://jsfiddle.net/us47d/