2017-06-30 37 views
0

我在表格中有三組不同的單選按鈕。如果我單擊單選按鈕,我沒有看到屬性選中設置爲true。我想知道在JQuery/JavaScript中處理這個問題的最佳方法是什麼?下面是例如:表單中的單選按鈕,如果選中,則取消選中其他選項?

$("input[type=radio]").on('click', function() { 
 
    var secondClick = true; 
 
    $(this).change(function() { 
 
    secondClick = false; 
 
    }); 
 
    $(this).click(function() { 
 
    if (secondClick) { 
 
     $(this).prop("checked", false); 
 
    } 
 
    secondClick = true; 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form name="myForm" id="myForm" method="POST" action="#"> 
 
    <div class="formItem"> 
 
    <label for="evaluation">Evaluation</label> 
 
    <input type="radio" name="frm_eval" id="frm_eval1" value="0" />Yes 
 
    <input type="radio" name="frm_eval" id="frm_eval2" value="1" />No 
 
    </div> 
 
    <div class="formItem"> 
 
    <label for="conditions">Conditions</label> 
 
    <input type="radio" name="frm_cond" id="frm_cond1" value="0" />Good 
 
    <input type="radio" name="frmhs_cond" id="frm_cond2" value="1" />Fair 
 
    <input type="radio" name="frm_cond" id="frm_cond3" value="2" />Poor 
 
    </div> 
 
    <div class="formItem"> 
 
    <label for="responses">Responses</label> 
 
    <input type="radio" name="frm_res" id="frm_res1" value="0" />Good 
 
    <input type="radio" name="frm_res" id="frm_res2" value="1" />Fair 
 
    <input type="radio" name="frm_res" id="frm_res3" value="2" />Poor 
 
    </div> 
 
</form>

功能以上沒有變化/設置檢查=真,我點擊的元素上的屬性。我希望看到所選元素的屬性選中爲true,並將所有其他複選框設置爲false。

+1

在第二組你有不同的名字'frmhs_cond'而不是'frm_cond ' – Omi

回答

0

你在條件第二輸入被評爲frmhs_cond代替frm_cond

<form name="myForm" id="myForm" method="POST" action="#"> 
 
      <div class="formItem"> 
 
       <label for="evaluation">Evaluation</label> 
 
       <input type="radio" name="frm_eval" id="frm_eval1" value="0" />Yes 
 
       <input type="radio" name="frm_eval" id="frm_eval2" value="1" />No 
 
      </div> 
 
      <div class="formItem"> 
 
       <label for="conditions">Conditions</label> 
 
       <input type="radio" name="frm_cond" id="frm_cond1" value="0" />Good 
 
       <input type="radio" name="frm_cond" id="frm_cond2" value="1" />Fair 
 
       <input type="radio" name="frm_cond" id="frm_cond3" value="2" />Poor 
 
      </div> 
 
      <div class="formItem"> 
 
       <label for="responses">Responses</label> 
 
       <input type="radio" name="frm_res" id="frm_res1" value="0" />Good 
 
       <input type="radio" name="frm_res" id="frm_res2" value="1" />Fair 
 
       <input type="radio" name="frm_res" id="frm_res3" value="2" />Poor 
 
      </div> 
 
     </form>

0

var radioInputs = $("#myForm input[type=radio]") 
 
radioInputs.on('change',function() { 
 
    var $this = $(this) 
 
    
 
    if ($this.is(':checked')) { 
 
    radioInputs.not($this).removeAttr('checked') 
 
    } 
 
})

相關問題