简体   繁体   中英

jQuery Select next option in Select fails after n-Times

I've got a select list with n options:

<select id="codeLeft" class="form-control">
   {% for code in code %}
      <option id="{{ code['try'] - 1}}">#{{ code['try'] }} --- {{ code['date'] }}</option>
   {% endfor %}
</select>

Now I've got two buttons which I want to use to iterate this list (left button prev item and right button next item). I've the last item is reached I want to start at the bottom again.

$('#button_left').click(function () {
    var idCode = $('#codeLeft').children(':selected').attr('id');
    var idNext = parseInt(idCode) - 1;

    if(idNext < 0){
        idNext = codeArray.length - 1;
    }

    $('#codeLeft option[id=' + idNext + ']').attr("selected", "selected");
});

$('#button_right').click(function () {
   var idCode = $('#codeLeft').children(':selected').attr('id');
    var idNext = parseInt(idCode) + 1;

    if(idNext === codeArray.length){
        idNext = 0;
    }

    $('#codeLeft option[id=' + idNext + ']').attr("selected", "selected");
});

My problem is that this only works n times (n is the length of code). Does anybody knows why?

First of all, you are assigning integers as ids and this is improper.

Dropdownlist shows the first attribute that has the attribute selected. Therefore, when you run it "n" times, all options would have the attribute selected as true and the browser wouldn't work no longer because it sees the current option as selected. Don't set attribute to selected. Instead, use prop:

$('#codeLeft option[id=' + idNext + ']').prop('selected', true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM