Comparing Grouped Select Options using jQuery

Go To StackoverFlow.com

1

I have several select tags on a page and I am grouping them using the data attribute to make sure those with the same data key can be compared. On submit, I want to check that the groups don't have the same option value selected. So imagine it was a depth chart and you had football quarterbacks and running backs listed and you want to modify their position on the depth chart. I can't have the two quarterbacks as #1 on the depth chart. All I need to do is alert the user...."Hey you can't have the same value for this position" but I'm not sure how to do the comparison to get to that point using jQuery.

Quarterback A
<select data-position="qb">
  <option>1</option>
  <option>2</option>
</select>

Quarterback B
<select data-position="qb">
  <option>1</option>
  <option>2</option>
</select>

Runningback A
<select data-position="rb">
  <option>1</option>
  <option>2</option>
</select>

Runningback B
<select data-position="rb">
  <option>1</option>
  <option>2</option>
</select>
2012-04-05 14:53
by TJnTN
Although it's not the same, can't you remove the taken position from related selects so is not available for selection (and add it back is becames available) - Claudio Redi 2012-04-05 14:57
That wouldn't work for what I'm trying to do - TJnTN 2012-04-05 15:01


0

I have just used classes to identify your groups, instead of the jQuery data attribute.

Quarterback A
<select class="qb">
  <option>1</option>
  <option>2</option>
</select>

Quarterback B
<select class="qb">
  <option>1</option>
  <option>2</option>
</select>

Runningback A
<select class="rb">
  <option>1</option>
  <option>2</option>
</select>

Runningback B
<select class="rb">
  <option>1</option>
  <option>2</option>
</select>

<button id="eval">evaluate</button>

Check this JS fiddle, i think it does what you want. If you need help explaining the code let me know,

http://jsfiddle.net/SnJP4/5/

I have set up a routine to bind to the click event of the "evaluate" button. If you were to add more positions, like wide reciever, etc. then just add the name of the class the the classes array. Here:

$('#eval').click(function() {
    var classes = ['qb','rb'];
    $(classes).each(function(index, el){
        var list = [];
        $('.'+classes[index]).each(function() {
            //alert($(this).val());
            list.push($(this).val());
        });
        list = list.sort();
        for (var i = 0; i < list.length - 1; i++) {
            if (list[i + 1] == list[i]) {
                alert('duplicate ' + classes[index]);
                break;
            }
        }
    });
});​
2012-04-05 15:29
by jeffery_the_wind
That's exactly what I was looking for.....thanks jeffery!! - TJnTN 2012-04-05 17:16
You can give me a 1up too if you want :-) - jeffery_the_wind 2012-04-05 17:28
I don't have enough reputation it says. :- - TJnTN 2012-04-07 00:43
Ads