3

I need a function that will compare two values from two drop-down selectors and if they are the same show a div. I'd like to use jQuery, if possible.

<select id="drop1">
   <option value="a">a
   <option value="b">b
   <option value="c">c
</select>

<select id="drop2">
   <option value="a">a
   <option value="b">b
   <option value="c">c
</select>
santa
  • 12,234
  • 49
  • 155
  • 255

2 Answers2

6
$("#myDiv").toggle($("#drop1").val() === $("#drop2").val());

Explanation: $("#dropX").val() gets the value of the selected element in that dropdown; the === compares them, giving true or false as appropriate; and $("myDiv").toggle(...) either shows or hides #myDiv depending on the passed value.

If you want to do this whenever the value changes, wrap this in $("#drop1, #drop2").change(function () { ... }); as in nickf's answer.

Domenic
  • 110,262
  • 41
  • 219
  • 271
  • Nice and handy overload of the toggle func., but why 3 ===? – Eric Fortis Dec 16 '10 at 17:55
  • `==` only compares the values, but coerces types if they are unequal (so e.g. `null == "" == undefined == 0`); `===` requires type equality as well (so `null === null`, but `null !== ""` and `null !== undefined` and so on). ALWAYS Using `===` is best practice. – Domenic Dec 16 '10 at 17:57
  • @Eric If only there were a web site that answered questions like that-- oh wait! http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use :) – Jason Orendorff Dec 16 '10 at 17:57
5
$('#drop1, #drop2').change(function() {
    $('#myDiv').toggle(
        $('#drop1').val() === $('#drop2').val()
    );
});
nickf
  • 537,072
  • 198
  • 649
  • 721