【问题标题】:Get & set drop down value using jQuery使用 jQuery 获取和设置下拉值
【发布时间】:2010-05-10 23:42:34
【问题描述】:

如果用户从下拉列表中选择一个选项,它将显示一个文本框,但如果他选择具有“其他”值的选项,则会出现一行来输入其他值。

我的代码工作正常,除非选项值不等于“其他”

<script type="text/javascript"><!--
function setAndReset(box) {
if(box.value == 'Other'){
    $("#ShowHide").hide();
}
document.FormName.hiddenInput.value = box.value;

}
//-->
</script>

<body bgcolor="#ffffff">
<form id="FormName" action="" method="get" name="FormName">
    <select name="choice1" size="1" onchange="setAndReset(this);">
    <option value="one">first</option>
    <option value="two">second</option>
    <option value="three">third</option>
    <option value="other">Other</option>
    </select>

    <input type="text" name="hiddenInput" value="">
    <tablt><tr id="ShowHide"><td>
        <input type="text" name="otherInput">
    </td></tr></table>
    <input type="submit" name="submitButtonName">
</form>
</body>

但它不显示/隐藏并且不在文本框中设置值。

如果它使用 jquery 解决,那么我会感谢你的代码。

谢谢。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    这样做:

    $(document).ready(function() {
        $("select[name=choice1]").change(function() {
           $(this).val() == 'other' ? $("#ShowHide").show() : $("#ShowHide").hide();
        });
    });
    

    并丢失内联 onchange 函数调用。 Try it here.

    【讨论】:

    • 你想要 $(this).val() == "other" 而不是 "Other"
    • @brad - 是的,我在做一个小演示时遇到了这个问题。
    【解决方案2】:

    我喜欢 karim79 的回答,但更喜欢它更紧凑一点:

    $(function() {
        $("select[name=choice1]").change(function() {
           $("#ShowHide").toggle($(this).val() === "other");
        });
    });
    
    • 不是$(document).ready(f),而是$(f),完全一样
    • 不要使用松散的==,而是使用=== 进行精确比较(在这种情况下,这无关紧要,但== 的行为可能会很奇怪,因此您应该在任何地方都避免使用它)
    • 使用toggle(b) 代替show()/hide()

    【讨论】:

    • 我没有意识到切换需要一个布尔值!简洁明了
    猜你喜欢
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2013-11-19
    相关资源
    最近更新 更多