2014-03-24 48 views
1

鑑於以下代碼(是的,我知道它可能與yii無關,但我添加了標籤,因此我使用實際生成的html更新了該問題):yii中的jquery:檢測單選按鈕丟失複選標記(選中狀態)

<script> 
$(function(){ 
    $('#widgetId-form input[name="valueType"]').change(function(){ 
     if ($(this).is(":checked")) 
     { 
      console.log("habilitando "+$(this).data("class")); 
      $("."+$(this).data("class")).prop("disabled", false); 
     } 
     else 
     { 
      console.log("deshabilitando "+$(this).data("class")); 
      $("."+$(this).data("class")).prop("disabled", true); 
     } 
    }).change(); 
}); 
</script> 
<div id="widgetId-dialog"> 
<form id="widgetId-form" action="/support/test" method="post"> 
    <div> 
     <input id="valueType-single" value="single" data-class="singleValueField" checked="checked" type="radio" name="valueType" /> 
     <label for="single">Valor simple</label> 
     <input size="6" class="singleValueField" type="text" value="" name="singleValue" id="singleValue" /> 
    </div> 
    <div> 
     <input id="valueType-range" value="range" data-class="rangeValueField" type="radio" name="valueType" /> 
     <label for="range">Rango (inicio:fin:intervalo)</label> 
     <input size="6" class="rangeValueField" type="text" value="" name="rangeValue_start" id="rangeValue_start" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_end" id="rangeValue_end" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_interval" id="rangeValue_interval" /> 
    </div> 
</form> 
</div> 

當收音機未選中時,它不會觸發change()。這意味着:僅在初始化(.ready())上禁用控件。 change()不會被丟失複選標記的控件單獨觸發。

問題:如何檢測單選按鈕何時丟失複選標記?

+0

你試過在「widgetId對話」附加一個? https://api.jquery.com/on/'$(「#widgetId-dialog」)。on('change','input [name =「valueType」]',function()......' –

+0

可能是一個愚蠢的問題,但是代碼是否寫成了?因爲它可以在繪製HTML之前執行javascript,請嘗試將其包裝在'$(document).ready()' – stakolee

+0

@stakolee'$(function (){'=='$(document).ready()''同樣來自jquery doc的 –

回答

0

這是一個概念問題。單選按鈕看起來像某個元素。欲瞭解更多信息,請看Why does jQuery .change() not fire on radio buttons deselected as a result of a namesake being selected?
因此,變化事件將始終只在新選定的元素上觸發,而不在取消選定的無線電上觸發。您可以治好你這樣的代碼:

$(function(){ 
    $('#widgetId-form input[name="valueType"]').change(function(){ 
     //could be also hardcoded : 
     $('input[name="' + $(this).attr("name") + '"]').each(function(){ 
       if ($(this).is(":checked")) 
      { 
       console.log("habilitando "+$(this).data("class")); 
       $("."+$(this).data("class")).prop("disabled", false); 
      } 
      else 
      { 
       console.log("deshabilitando "+$(this).data("class")); 
       $("."+$(this).data("class")).prop("disabled", true); 
      } 
     }); 
    }); 

    $('#widgetId-form input[name="valueType"]:first').change(); 
}); 

你可以在http://jsfiddle.net/jg6CC/檢查。問候另一個路易斯M.;)

+0

如果你有很多收音機,你可以記住上次選擇的收音機,並在這個和新選擇的收音機上應用更改。這樣就不需要遍歷所有的東西(並且保存性能。即使你不應該在迭代中得到性能問題) –

+0

我以類似於這裏描述的方式解決了(我放棄了,並得出了相同的結論) 。然而,對我來說,愚蠢的是,HTML收音機不會觸發單選按鈕未被選中的變化()(從這個意義上說,記住之前的收音機根本不需要)。 –