exclude value from one select box based on value of other selectbox

梦想与她 提交于 2019-12-13 20:18:16

问题


I am trying to exclude from one select list what the user has chosen in the other select list.

It is a list of 2 questions and the user can not select the same question in both select lists

For some reason it works for the first couple of selections but then it start altering the value of the second box to a value it was not. It works fine for a couple of selections on both but if you keep selecting between the 2 it start to return incorrect results

Below is the jquery code but here is the Link to Fiddle to complete code

var q1 = "#q1";
var q2 = "#q2";
var questions = {"1":"Question 1","2":"Question 2","3":"Question 3","4":"Question 4"}

function rebuildList(option,id) {
    var currentValue = $(id).val();
    $(id).empty();
    $(id).append($('<option></option>').val(0).html("Select"));

    $.each(questions, function (key, value) {
        if (key != option) {
            $(id).append($('<option></option>').val(key).html(value));
        }
    });

    //set the value back to what it was before emptying the list
    var setter;
    if (currentValue == "") {
        setter = id + " option:eq(0)";
    } else {
        setter = id + " option:eq(" + currentValue + ")";
    }


    $(setter).prop('selected', 'selected');
}



$(document).ready(function () {
    $(q1).change(function () {
        rebuildList($(this).val(), q2);  
        return false;
    });

    $(q2).change(function () {
        rebuildList($(this).val(), q1);  
        return false;
    });
});

回答1:


The problem happens when you use eq(). I modifed that part and the code works fine,

if (currentValue == "") {
    $(id).val(0)
} else {
    $(id).val(currentValue)
}

Check here, http://jsfiddle.net/muthkum/BsHHz/3/



来源:https://stackoverflow.com/questions/13717012/exclude-value-from-one-select-box-based-on-value-of-other-selectbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!