2013-07-04 42 views
0

我有很多選擇的形式。jquery添加/刪除多個輸入從多個選擇(下拉列表)

我想在窗體中添加一些選擇「其他」選項。當選擇「其他」時,它會顯示一個隱藏的輸入。

$(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」 S

所有的選擇都是一個表內的TD內。

如何確保在選擇「其他」時,它只顯示該TD內的隱藏輸入?

回答

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對象,或元件過濾。
+0

作品非常好,謝謝。 – monsey11

+0

你知道我如何在他們展示時向他們添加和刪除「必需」類嗎? – monsey11

+0

要添加或刪除類,可以使用toggleClass(「classname」)或addClass(「classname」)/ removeClass(「classname」)。 – krishgopinath