如果两个选择值都已选择运行功能

时间:2014-04-10 11:53:47

标签: javascript jquery

如果之前的12个下拉列表中有值,我会尝试填充并显示select

我似乎无法使我的if语句正确,但有人可以看到我可能做错了什么吗?

$('select').on('change',function(){

if( $('.player1') != null || $('.player2') != null ){

    // If both players have been selected, show the winner dropdown and populate it with the value from player1 and player 2.
    $('.winner').show();

}

});

http://jsfiddle.net/kbPLn/1/

4 个答案:

答案 0 :(得分:1)

jQuery对象永远不会等于null。您可以做的是检查集合的length属性。此外,您似乎想要&&而不是||

if ($('.player1>option:selected').length && $('.player2>option:selected').length) {

编辑:您需要做的是检查它是否有选定的子选项。

答案 1 :(得分:0)

在检查否定值时需要使用&&

答案 2 :(得分:0)

你拥有的案例永远不会为空..(因为你没有检查.val ...而且,他们总是有一个val)在这里更新你的HTML +你的选择器:

http://jsfiddle.net/kbPLn/5/

if( $('.player1>option:selected').val() != "No value" && $('.player2>option:selected').val() != "No value" ){

<强>更新 http://jsfiddle.net/kbPLn/9/

        var first = $('.player1>option:selected').val(),
         second =$('.player2>option:selected').val();

        $('.winner').find('option:first').val(first).html(first);
        $('.winner').find('option:not(:first)').val(second).html(second);
        $('.winner').show();

答案 3 :(得分:0)

 Try this. This may help you:
 $('select').on('change', function () {
            $('select[name="winner"]').html('');
            if ($('.player1') != null || $('.player2') != null) {

                // If both players have been selected, show the winner dropdown and populate it with the value from player1 and player 2.
                $('.winner').show();

                //$('.winner').
            }
            $('select[name="winner"]').append('<option value="' + $(".player1").val() + '">' + $(".player1").val() + '</option>');
            $('select[name="winner"]').append('<option value="' + $(".player2").val() + '">' + $(".player2").val() + '</option>');
        });