问题
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