2013-02-15 37 views
1

在我的網頁我具備多形式,當我點擊單選按鈕「disabled_radio」我願意單選按鈕「radio_enabled_disabled」被禁用,但相對的形式ID。jQuery來形成

<td> 
<form method="post" name="form1" id="form1" action="send.php"> 
    <div id="choice"> 
    <input type="radio" name="enabled_radio" value="yes" />YES 
    <input type="radio" name="disabled_radio" value="no" />NO 
    </div> 
    <div id="mydiv"> 
    <input type="radio" name="radio_enabled_disabled" /> 
    </div> 
</form> 
</td> 
<td> 
<form method="post" name="form2" id="form2" action="send.php"> 
    <div id="choice"> 
    <input type="radio" name="enabled_radio" value="yes" />YES 
    <input type="radio" name="disabled_radio" value="no" />NO 
    </div> 
    <div id="mydiv"> 
    <input type="radio" name="radio_enabled_disabled" /> 
    </div> 
</form> 
</td> 
+5

您的HTML已滿錯誤:重複使用的ID,電臺組名稱未使用。 – 2013-02-15 11:42:43

回答

1

首先,你需要使用它們分組無重複使用的ID和無線電名固定的HTML:

<form method="post" name="form1" id="form1" action="send.php"> 
    <input type="radio" name="enable_radio" value="yes">YES 
    <input type="radio" name="enable_radio" value="no">NO 
    <input type="radio" name="radio_enabled_disabled"> 
</form> 
<form method="post" name="form2" id="form2" action="send.php"> 
    <input type="radio" name="enable_radio" value="yes">YES 
    <input type="radio" name="enable_radio" value="no">NO 
    <input type="radio" name="radio_enabled_disabled"> 
</form> 
<form method="post" name="form3" id="form3" action="send.php"> 
    <input type="radio" name="enable_radio" value="yes">YES 
    <input type="radio" name="enable_radio" value="no">NO 
    <input type="radio" name="radio_enabled_disabled"> 
</form> 

然後,你可以這樣做:

$('[name=enable_radio]').change(function(){ 
    $(this).parent().find('[name="radio_enabled_disabled"]') 
     .prop('disabled',this.value=='yes') 
}); 

Demonstration

0

您的HTML有一些問題,但我會假設這只是一些示例鱈魚你包括顯示你正在嘗試做什麼。

如果您的無線電元素是您希望啓用/禁用的窗體的子項,則可以使用parent() function在DOM中向上一級,然後到達表單元素。

$('input.disabled_radio').on('click',function(){ 
    $(this.parent().find('input[name="radio_enabled_disabled"]').prop('disabled','disabled'); 
}); 

此代碼將找到相對父窗體元素併爲其中包含的每個輸入元素設置disabled屬性。

個人而言,我喜歡那樣,我可以用我的代碼冗長。我發現這大大提高了可讀性。所以我會推薦使用jQuery的closest() function而不是parent()closest()函數要求您指定要查找的父元素的類型。因此,代碼會是這個樣子 -

$('input.disabled_radio').on('click',function(){ 
    $(this.closest('form').find('input[name="radio_enabled_disabled"]').prop('disabled','disabled'); 
}); 

之後,重新啓用的單選按鈕,您將需要刪除disabled屬性。爲此,您可以使用此功能 -

.prop('disabled','');