有条件地显示基于用户选择框选择的单选按钮

时间:2013-08-30 00:11:12

标签: javascript jquery

下面是一些示例代码 - 尝试仅在用户从选择框中选择特定选项时才显示单选按钮。请参阅指定要求的脚本标记中的两条注释。

<!DOCTYPE HTML>
<html>
<head>
    <style>
    ul {list-style-type: none;}
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script type="text/javascript">
        //what jQuery code is needed here so that the following occurs?
        //1. the label for the radio buttons and the radio buttons themselves only appears when the user picks Formula Type 3 from the select box
        //2. when the radio buttons and label are not displayed, the space they were in remains but it just looks empty (the word "placeholder", in the third li tag, does NOT move up underneath the select box)
    </script>
</head> 
<body>
    <ul>
        <li>
            <label for="FormulaType">Formula Type</label>
            <select name="FormulaType" id="FormulaType">
                <option value=""></option>
                <option value="Type1">Type1</option>
                <option value="Type2">Type2</option>
                <option value="Type3">Type3</option>
                <option value="Type4">Type4</option>
            </select>
        </li>
        <li>
            <label for="OutputFat">Output Fat Is</label>
            <input type="radio" name="OutputFat" value="low">lowest
            <input type="radio" name="OutputFat" value="high">highest       
            </radio>
        </li>
        <li>
            placeholder
        </li>
    </ul>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

尝试

jQuery(function(){
    $('#FormulaType').change(function(){
        var $this = $(this);
        $this.closest('li').next().css('visibility', $this.val() == 'Type3'? 'visible' : 'hidden')
        //if don't want to preserve the space
        //$this.closest('li').next().toggle($(this).val() == 'Type3')
    }).triggerHandler('change')
})

演示:Fiddle

相关问题