使用jQuery,我想获得两个无线电组的值,如果它的任何值改变了

时间:2017-12-26 10:47:51

标签: jquery

我想听听广播组的变化事件。如果其中任何一个发生变化,我需要通过ajax发送它们。



$('input:radio[name=emp_m_status]','input:radio[name=emp_gender]').change(function() {
  var gender = document.getElementByName("emp_gender");
  var married = document.getElementByName("emp_m_status");
  console.log(gender, married);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

emp_m_status:
<br>
<label><input name="emp_m_status" type="radio" value="Married" checked>Married </label><br/>
<label><input name="emp_m_status" type="radio" value="Divorced">Divorced </label><br/><br/> emp_gender:

<br>
<label><input name="emp_gender" type="radio" value="Male" checked>Male </label><br>
<label><input name="emp_gender" type="radio" value="Female">Female </label><br>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

选择器错误。您正在使用context selector而不是Multiple selector

$('input:radio[name=emp_m_status],input:radio[name=emp_gender]')
                               //^^

上述选择器中input也是多余的。

此外,使用:checked selector获取所选的无线电值。

var emp_m_status = $(':radio[name=emp_m_status]:checked').val();  

$(':radio[name=emp_m_status],:radio[name=emp_gender]').change(function() {

  var emp_m_status = $(':radio[name=emp_m_status]:checked').val();
  var emp_gender = $(':radio[name=emp_gender]:checked').val();

  console.clear();
  console.log('emp_m_status: ', emp_m_status);
  console.log('emp_gender: ', emp_gender);
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

emp_m_status:
<br>
<label><input name="emp_m_status" type="radio" value="Married" checked>Married </label><br/>
<label><input name="emp_m_status" type="radio" value="Divorced">Divorced </label><br/><br/> emp_gender:

<br>
<label><input name="emp_gender" type="radio" value="Male" checked>Male </label><br>
<label><input name="emp_gender" type="radio" value="Female">Female </label><br>