【问题标题】:jquery add/remove multiple inputs from multiple selects (dropdowns)jquery从多个选择中添加/删除多个输入(下拉菜单)
【发布时间】:2013-07-04 00:44:11
【问题描述】:

我在一个表单中有很多选择。

我想在表单中的一些选择中添加“其他”选项。选择“其他”时,它显示隐藏的输入。

$(document).ready(function(){

$(".SelectOther").append('<option value=-1>Other</option>');
$(".OtherDiv").hide();
    $(".SelectOther").change(function()
    {
        if($(".SelectOther option:selected").text() == "Other")
        {
            $(".OtherDiv").show("slide", { direction: "up" }, 1000);
        }
        else
        {
            $(".OtherDiv").hide("slide", { direction: "down" }, 1000);
        }
    });

});

尚未测试此代码,但这会打开所有隐藏的“OtherDiv”

所有选择都在表中的 TD 内。

如何确保选择“其他”时仅显示该 TD 中的隐藏输入?

【问题讨论】:

    标签: javascript jquery forms jquery-ui show-hide


    【解决方案1】:

    解决方案:

    使用$(this)。通过这种方式,您将知道您处于正确的上下文中。

    $(document).ready(function(){
    
       $(".SelectOther").append('<option value=-1>Other</option>');
       $(".OtherDiv").hide();
       $(".SelectOther").change(function() {
         var otherDiv =  $(this).closest("tr").find(".OtherDiv"); // find the .otherdiv within the tr
         if($(this).find("option:selected").text() == "Other") //find the selected option
         {
               otherDiv.show("slide", { direction: "up" }, 1000);
         }
         else
         {
               otherDiv.hide("slide", { direction: "down" }, 1000);
         }
        });
    
    });
    

    编辑:

    要添加或删除类,您可以使用toggleClass("classname"),或addClass("classname")/removeClass("classname")

    更多关于这里使用的东西的信息:

    $(this)

    find()

    • 文档:http://api.jquery.com/find/
    • 它的作用:获取当前匹配元素集中每个元素的后代,由选择器、jQuery 对象或元素过滤。

    【讨论】:

    • 你知道我如何在它们显示时添加和删除“必需”类吗?
    • 添加或删除一个类,可以使用toggleClass("classname"),或者addClass("classname")/removeClass("classname")。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2015-11-03
    相关资源
    最近更新 更多