bland_dan bland_dan - 2 months ago 7
jQuery Question

Comparing input fields using JQuery

I currently have an input form. There are two entries for each input class as follows:

<form>
<input type="text" name="firstname_a" class="firstname" disabled="disabled" />
<input type="text" name="firstname_b" class="firstname" />
<input type="text" name="surname_a" class="surname" disabled="disabled" />
<input type="text" name="surname_b" class="surname" />
<input type="submit" value="submit" />
</form>


On submission I want JQuery to check whether or not value a matches value b (value a has been entered by the end user, value b has been entered by a outworker working for a vetting company). The form could have upto 470 input fields, these are stored in a database dependant upon the type of vetting being carried out. I don't, therefore, want to have to type out 470 times!:

if($('input["name=firstname_a"]').val() == $('input["name=firstname_a"]').val())
{
// do something
}
else
{
// do something else
}


Rather I would like to find a dynamic way to do this, possibly using the serializeArray() function, but I'm struggling! All or any help would be greatly appreciated.

Answer

You can cycle through .each input ending in _a and do the comparison with its _b counterpart:

$('#target').submit( function() {

    // Iterate over each input with name ending in _a
    $('input[name$="_a"]').each( function() {

        // Get the base name by removing _a
        var name = $(this).attr('name').replace(/_a$/, '');

        // Compare _a to _b
        if( $('input[name="'+name+'_a"]').val() != $('input[name="'+name+'_b"]').val()) {
             alert(name+" field does not match!");   
        }
    });

    return false;
});

Example:

http://jsfiddle.net/jtbowden/yqMGG/

Here is a version where all mismatches are saved and alerted at the end:

http://jsfiddle.net/jtbowden/amsJj/

Or a version that highlights the errors:

http://jsfiddle.net/jtbowden/V8xJX/