选择框打开输入框jQuery

时间:2012-03-04 17:25:40

标签: jquery

我正在尝试打开一个选择框,在选择某些选项时显示输入框。

这是我的代码:

$("document").ready(function() {
    $('input.other').hide();
    $('#amount').change(function() {
        // var val = $(this).find('option:selected').text();
        //alert(val);
        var selectedValue = $(this).find(":selected").val();
        //alert(selectedValue);
        if( $(this).selectedValue == '25.00') {
            // only if the radio button has a dob-field
            $('input.other').show();// show only the following first
        }
    });
});

3 个答案:

答案 0 :(得分:2)

您可以使用下面的选择器直接定位option元素中的选定#amount,并找到它的值并在if语句中对其进行比较。

问题中代码的问题是$(this).selectedValue,其中$(this)指的是#amount,而不是optionselectedValue是变量,并且应该直接使用,但是这里不一定要使用变量,因为它完全可读并且直接在if语句中执行所有操作。

$('input.other').hide();
$('#amount').on('change', function(){
    if( $(':selected', this).val() == '25.00') {
        $('input.other').show();
    }
});

答案 1 :(得分:1)

使用selectedValue检查$(this).selectedValue

if( selectedValue == '25.00') { // only if the radio button has a dob-field
 $('input.other').show();// show only the following first
}

这是一个完整的工作片段

$(document).ready(function() {
    $('input.other').hide();
        var selectedValue = $(this).find(":selected").val();
        if( selectedValue == '25.00') {
            // only if the radio button has a dob-field
            $('input.other').show();// show only the following first
        }
    });
});

答案 2 :(得分:1)

您可以直接在.val()上使用SELECT,而不是选择:selected OPTION(假设#amountSELECT元素) :

var input = $('input.other').hide();
$('#amount').change(function() {
    if( $(this).val() == '25.00') {
        input.show();
    }
});

演示:http://jsfiddle.net/bj6MJ/

已添加:如果用户选择“25.00”以外的其他内容,您希望再次隐藏它,则可以使用toggle()

var input = $('input.other').hide();
$('#amount').change(function() {
    input.toggle( $(this).val() == '25.00' );
});

演示:http://jsfiddle.net/bj6MJ/1/

相关问题