jquery添加/删除多个选择中的多个输入(下拉列表)

时间:2013-07-04 00:44:12

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

我在表单中有很多选择。

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

$(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中的隐藏输入?

1 个答案:

答案 0 :(得分: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对象或元素过滤。