xXPhenom22Xx
xXPhenom22Xx

Reputation: 1275

Compare value of 2 SELECT boxes using jQuery

I have 2 HTML SELECT boxes (id=Select1 and Select2). I would like to have jQuery compare the value of Select2 against Select1 after an onChange event of Select2.

If Select1 and Select2 have the same value then clear the value in Select2 or reset it and then a simple javascript alert window?

I am a PHP developer and pretty much a noob with jQuery so any help is appreciated.

Thanks,

Upvotes: 1

Views: 8950

Answers (3)

Elliot B.
Elliot B.

Reputation: 17651

Full working example:

<html>
<head>
<script>
    $(document).ready(function() {
        $('#Select2').change(function() {
            if ($(this).val() == $('#Select1').val()) {
                alert('same');
            } else {
                alert('different');
            }
        });
    });

</script>
</head>
<body>

    <select id="Select1">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>

    <select id="Select2">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>

</body>
</html>

Upvotes: 1

Marius Ilie
Marius Ilie

Reputation: 3323

$("#Select2").change(function(){
  if($(this).val() == $("#Select1").val()) {
    alert('Duplicate value');
    $(this).val('');
  }
});

Upvotes: 3

Ryan
Ryan

Reputation: 28187

$('#select2').change ( function () {
    if ( $('#select2').val() == $('#select1').val() ) {
         alert ( 'do whatever');
    }
});

Take a look at change() and val().

Upvotes: 2

Related Questions