5xum
5xum

Reputation: 5545

Catch attribute change on automatically changed elements

I want to create two selections on my webpage which will be connected to each other so that both selections will always be the same. Let me explain in a mock example:

I have a webpage with two selects:

<select class="myselector">
    <option value='1'>1
        <br>
    </option>
    <option value='2'>2
        <br>
    </option>
</select>
<select class="myselector">
    <option value='1'>1
        <br>
    </option>
    <option value='2'>2
        <br>
    </option>
</select>

Note: in reality, I have more than just the two selects and I want them all to be connected.

Now, I want the webpage to automatically set the second selector to the value of the first if the first is changed. I also want to perform some other things on the select that has changed, so I also want the change event to trigger on the other selector. My first thought was simply to do this:

function valChange() {
    myfun();
    $('.myselector').val($(this).val());
}
$('.myselector').on('change', valChange);

My next thought was to add $('.myselector').change(); to the end of the valChange function, but this (naturally) causes an infinite loop of change events.

My question is, therefore:

How can I trigger the change event in only the elements that have been changed automatically (not by a user)?

I think it could be done by having both the change and the click event, but that just seems wrong and ugly to me.


EDIT: I found a way to solve my problem through the use of jquery selectors. If there exists a more elegant way of solving the problem, I will still be happy to see it though.

function valChange() {
    myfun()
    var others = $('.myselector[value!=' + $(this).val() + ']');
    others.val($(this).val());
    others.change();
}

$('.myselector').on('change', valChange);

JSfiddle for my solution:

http://jsfiddle.net/5xum/svjbdxgs/

Upvotes: 0

Views: 52

Answers (1)

mulla.azzi
mulla.azzi

Reputation: 2676

you can use each method of jquery

function valChange() {
     var _this = $(this)
     $('.myselector').each(function(){
          myFun();
          $(this).val(_this.val());
     });
}
$('.myselector').on('change', valChange);

here is fiddle for the same fiddle link

Upvotes: 1

Related Questions