我有两个广播组,我需要在更改时获得任何单选按钮的值。但是当点击第二组时,jQuery只返回第一组广播项的值。
感谢您提出的建议:将无线电添加到.options选择器,但我还有其他表单元素,例如我监视的选择更改为。我们可以用变量添加它吗?
$('.options').change(function() {
var checkedInput = $('.options input:checked').val();
console.log('Checked input is : '+ checkedInput);
alert('Checked input is : '+ checkedInput);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="options">
<input type="radio" name="group-one" value="pink" checked >
<label for=""> pink </label>
<input type="radio" name="group-one" value="blue">
<label for=""> blue </label>
<input type="radio" name="group-one" value="black">
<label for=""> black </label>
<hr>
<input type="radio" name="group-two" value="orange">
<label for=""> orange </label>
<input type="radio" name="group-two" value="banana">
<label for=""> banana </label>
<input type="radio" name="group-two" value="apple">
<label for=""> apple </label>
</div>
&#13;
答案 0 :(得分:1)
非常接近,只有一个div与.options类,所有表单元素都在其中。我只想要一个var。
中的单选按钮的值
$(function () {
var eleToSelect = '.options :radio';
$(eleToSelect).change(function() {
var checkedInput = $(this).val();
console.log('Checked input is : '+ checkedInput);
alert('Checked input is : '+ checkedInput);
$('#result').text('Checked input is : '+ checkedInput); // for the snippet
});
eleToSelect = '.options1 select';
$(eleToSelect).change(function() {
var checkedInput = $(this).val();
console.log('Checked input is : '+ checkedInput);
alert('Checked input is : '+ checkedInput);
$('#result').text('Checked input is : '+ checkedInput); // for the snippet
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="options">
<input type="radio" name="group-one" value="pink" checked >
<label for=""> pink </label>
<input type="radio" name="group-one" value="blue">
<label for=""> blue </label>
<input type="radio" name="group-one" value="black">
<label for=""> black </label>
<hr>
<input type="radio" name="group-two" value="orange">
<label for=""> orange </label>
<input type="radio" name="group-two" value="banana">
<label for=""> banana </label>
<input type="radio" name="group-two" value="apple">
<label for=""> apple </label>
<br>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>