2012-11-01 35 views
0

有一個隱藏/可見的基於無線電的字段。以前隱藏的字段的jquery驗證器

因此而載入網頁,我們使其可見基於無線電值

$(document).ready(function() { 

     if(edit) { 
      populateData(); 
     } 

     $(radio).change(function(){ 
      //here also we show hide text box based on radio value 
     }) 

     function PopulateData() { 
      //This does select radio and based on same show/hide text field 
     } 

     $("myForm").validate(); // attaching validate . At this point field could be hidden or visible 


     $(savebutton).click(function(){ 

     /*This does not validate text 
      field (visibleBasedOnRadio) which was hidden and made visible by either of above */ 

      if($("myForm").valid() == false) { 
       return false; 
      } 
     }); 
    }); 

<form id="myForm"> 
<radio> 
    <option 1> 
    <option 2> 
</radio> 

<input type="text" id="visibleBasedOnRadio" class="required" style="display:none"/> 
</form> 

回答

0

你使用的是什麼框架的顯示邏輯,我不知道隱藏。我會試着儘可能通用。

讓我們在窗體中添加兩個變量。

  1. radioButtonValue - 保存所選單選按鈕的值。比如說,選項1或選項2。您可以爲此字段設置默認值,以便在頁面加載時默認選擇該特定選項。
  2. valueOfTheVisibleField - 該字段保存輸入文本框的值,該文本框在選擇單選按鈕後可見。

    <form> 
        <input type="radio" name="radioButtonValue" value="option1"> Option 1<br> //This is checked. 
        <input type="radio" name="radioButtonValue" value="option2"> Option 2<br> 
        <input type="text" id="visibleBasedOnRadio" class="required" name="valueOfTheVisibleField" style="display:none"/> 
    </form> 
    

現在您的驗證檢查的單選按鈕的第一個值。只有當它的值是選項2時,即,當顯示所需字段時......只有檢查文本框值是否存在。如果沒有做任何與valueOfTheVisibleField字段相關的任何事情,因爲它隱藏了。