Joseph
Joseph

Reputation: 348

changing value of a selected option

I have a some selects in a class, when the change event happens on any of those selects I want to do the following : search all the selects for the selected value on which the change event occurred, when found I want to swap the two values.

Ill give an example :

<div id="l1col1" class="selects1">
    <select onChange='swap(newVal, oldVal);'>
        <option selected>3</option>
        <option>2</option>
        <option>1</option>
    </select>
</div>

<div id="l1col2" class="selects1">
    <select onChange='swap(newVal, oldVal);'>
        <option selected>2</option>
        <option>3</option>
        <option>1</option>
    </select>
</div>

<div id="l1col3" class="selects1">
    <select onChange='swap(newVal, oldVal);'>
        <option selected>1</option>
        <option>2</option>
        <option>3</option>        
    </select>
</div> 

None of my selects can have the same value of the other : there can never be 1 or 2 or 3 more then once.

this is my swap function

function swap (x,y){    
    //alert($(x).find(":selected").text()); 
    var tt = $(x).find(":selected").text();         
    alert(tt + y);
    $('.selects2 :selected:contains("' + tt + '")').text("' + y + '");
}

The problem is that when i call the change event lets say on the first select which contains 3 and change it with 1 , the swap function changes the select that has 1 as selected to 3 BUT also changes again the select which i changed to 3 again .

Can u help me work around this ? I hope I was clear enough

Upvotes: 1

Views: 94

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337550

Firstly, use jQuery to attach your events in stead of ugly inline handlers. Secondly, you can use data attributes to store the old value to compare to. Try this:

$('.selects1 select')
    .each(function() {
        var $this = $(this);
        $this.data('old-value', $this.val());
    })
    .change(function() {
        var $this = $(this);
        var newValue = $this.val();
        var oldValue = $this.data('old-value');
        $('.selects1 select').not(this).filter(function() {
            return $(this).val() == newValue;
        }).val(oldValue).data('old-value', oldValue);
        $this.data('old-value', newValue);
    });

Example fiddle

Upvotes: 1

Related Questions