2016-06-28 83 views
0

我有下面的代碼包含一個下拉列表和兩個文本框與ids「OtherName」和「OtherDesc」。我想從下拉列表中選擇除「other」之外的任何值時刪除/刪除兩個文本框。這是我的代碼,但它不工作任何想法爲什麼?刪除/刪除基於Dropbox選擇的文本框

<div class="form-group"> 
      @Html.LabelFor(model => model.CategoryId, "Category", htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.DropDownList("CategoryId", null, htmlAttributes: new { @class = "form-control" }) 
       @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" }) 
      </div> 
     </div> 


      <div id="OtherName" class="form-group" > 
       @Html.LabelFor(model => model.tbl_Category.CategoryName, htmlAttributes: new { @class = "control-label col-md-2" }) 
       <div class="col-md-10"> 
        @Html.EditorFor(model => model.tbl_Category.CategoryName, new { htmlAttributes = new { @class = "form-control" } }) 
       </div> 
      </div> 

     <div id="OtherDesc" class="form-group"> 
      @Html.LabelFor(model => model.tbl_Category.CategoryDesc, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.tbl_Category.CategoryDesc, new { htmlAttributes = new { @class = "form-control" } }) 
      </div> 
     </div> 

JQUERY

$(document).ready(function() { 
     //this line fires no matter what 
     $("#OtherName").hide(); 
     $("#OtherDesc").hide(); 

     $("#CategoryId").change(function() { 
      var value = document.getElementById("CategoryId").value; 
      if (value == "1011") { 
       $("#OtherName").show(); 
       $("#OtherDesc").show(); 
      } 
      else { 
       $("#OtherName").remove(); 
       $("#OtherDesc").remove(); 
      } 
     }); 
    }) 

回答

0

.remove()去除DOM completely.You元件需要使用.hide(),而不是刪除的元素。

您也可以通過多種方式優化您的代碼。像

1)使用點擊的選擇方面,而不是通過ID又一次的

2)使用多個選擇同時針對元素,然後顯示/隱藏他們一個電話。

$("#CategoryId").change(function() { 
     var value = this.value; 
     $("#OtherName,#OtherDesc").toggle(value == "1011"); 
}); 
+0

在你的情況,你錯過了最初的隱藏和有選擇的元素然後兩次,在你的事件處理程序的內部和外部。或者你手動觸發'change'事件一次。 – eisbehr

+0

@eisbehr:我只修改了選擇處理程序。其他代碼沒有問題:) –

1

一些建議如何修改代碼:

  1. 您可以將元素選擇結合起來。使用hide代替remove。否則你的元素將永遠消失。

  2. 你已經使用jQuery,所以你沒有得到超過jQuery的價值嗎?

  3. 因爲你只需要一次值,所以不需要變量聲明value

  4. 對於$(document).ready(function() {});有一個簡寫$(function() {});

代碼:

$(function() { 
    var boxes = $("#OtherName, #OtherDesc").hide(); 

    $("#CategoryId").change(function() { 
     if($(this).val() == "1011") 
      boxes.show(); 
     else 
      boxes.hide(); 
    }); 
}); 

甚至更​​短,你可以用toggle代替showhide去:

$(function() { 
    var boxes = $("#OtherName, #OtherDesc").hide(); 

    $("#CategoryId").change(function() { 
     boxes.toggle($(this).val() == "1011"); 
    }); 
}); 
+0

我需要刪除因爲我有一個錯誤,否則。有沒有辦法刪除? – user2217303

+0

如果您將其移除,則無法輕鬆將其移回。它們從文檔中刪除。你有什麼錯誤?也許什麼時候能解決它們。 – eisbehr

+0

隱藏文本框的字段被賦值爲null,因此我創建的東西不會被創建,它不會被驗證。但如果我不把它們的工作正常,如果我選擇其他它也可以正常工作,因此我想刪除。 – user2217303