2010-11-03 104 views
20

我需要爲一組單選按鈕註冊一個處理程序。我使用JQuery,並希望它的.change方法可以實現這一點。但是我沒有經歷過期望的行爲。如何使用JQuery監聽RadioGroup選定值的更改?

這是我寫的一個片段。可悲的是,「radioValueChanged」僅在初始加載時被調用。選擇true/false不會觸發處理程序。

<html> 
<script src="jquery-1.4.2.min.js" type="text/javascript"></script> 

<form id="myForm"> 
    <div id="Question1Wrapper"> 
     <div> 
      <input type="radio" name="controlQuestion" id="valueFalse" value="0" /> 
      <label for="valueFalse"> 
       False</label> 
     </div> 
     <div> 
      <input type="radio" name="controlQuestion" id="valueTrue" value="1" /> 
      <label for="valueTrue"> 
       True</label> 
     </div> 
    </div> 
    <div id="Question2Wrapper"> 
     <div> 
      <label for="optionalTextBox"> 
       This is only visible when the above is true</label> 
      <input type="text" name="optionalTextBox" id="optionalTextBox" value="" /> 
     </div> 
    </div> 

    <script type="text/javascript"> 
     jQuery(document).ready(function() 
     { 
      $("#controlQuestion").change(radioValueChanged('controlQuestion')); 
     }) 

     function radioValueChanged(radioName) 
     { 
      radioValue = $('input[name=' + radioName + ']:checked', '#myForm').val(); 

      alert(radioValue); 

      if(radioValue == 'undefined' || radioValue == "0") 
      { 
       $('#Question2Wrapper:visible').hide(); 
      } 
      else 
      { 
       $('#Question2Wrapper:visible').show(); 
      } 
     } 
    </script> 
</form> 

回答

33

這裏有幾個問題。

  1. 您立即運行radioValueChanged('controlQuestion')腳本執行時,因爲這是一個方法調用,而不是一個功能分配。

  2. 選擇器$("#controlQuestion")是錯誤的,您沒有任何元素的ID爲controlQuestion

  3. radioValueChanged方法沒有正確處理值,因爲它們會傳遞給jQuery事件處理程序。

你可以嘗試像以下:

jQuery(document).ready(function() 
    { 
     $("input[name='controlQuestion']").change(radioValueChanged); 
    }) 

    function radioValueChanged() 
    { 
     radioValue = $(this).val(); 

     alert(radioValue); 

     if($(this).is(":checked") && radioValue == "0") 
     { 
      $('#Question2Wrapper').hide(); 
     } 
     else 
     { 
      $('#Question2Wrapper').show(); 
     } 
    } 

說實話我不知道如果這是你與if語句尋找實際的邏輯,但希望這將提供這是您糾正當前代碼的基礎。

+0

非常感謝。正如你可以告訴javascript/jquery相當新/生鏽。所以'#'總是加一個id而不是名字......很高興知道:)「$(this).is(」:checked「)到底是做什麼的?我想我想要的是與之相反的。如果沒有選擇任何值,我想隱藏這個問題 – Justin 2010-11-03 21:25:37

+1

@Justin是的,選擇器實際上遵循CSS選擇器規則,你可以搜索w3的css選擇器..層次結構,名稱,ID等。另外'is'是一個jQuery函數:http ://docs.jquery.com/Is(雖然我沒有在api.jquery.com上找到關於我的內容) – 2010-11-03 21:36:01

+0

'is()'*絕對*在api子域:[api.jquery.com /is/](http://api.jquery.com/is/) – 2010-11-03 22:18:36

0
$('#Question2Wrapper:visible').show(); 

取出:可見,這將只選擇它,如果格已經顯示,在影響,如果它是隱藏它永遠不會被顯示。

$('#Question2Wrapper').show(); 

我離題了,我覺得Quintin擊中了大部分要點。這裏有幾個問題正在進行。