根据另一个选择框的值从一个选择框排除值 [英] exclude value from one select box based on value of other selectbox

查看:150
本文介绍了根据另一个选择框的值从一个选择框排除值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个选择列表中排除用户在另一选择列表中选择的内容.

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

这是2个问题的列表,用户不能在两个选择列表中都选择相同的问题

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

由于某种原因,它适用于前两个选择,但随后它开始将第二个框的值更改为不适用的值.在两个选项上都可以很好地工作,但是如果您继续在两个选项之间进行选择,则会开始返回错误的结果

下面是jquery代码,但这是链接到Fiddle 来完成代码

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;
    });
});

推荐答案

使用eq()时会发生此问题.我修改了该部分,代码工作正常,

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)
}

在此处检查 http://jsfiddle.net/muthkum/BsHHz/3/

这篇关于根据另一个选择框的值从一个选择框排除值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆