有一个包含4列的表格。每列都有一些单选按钮。用户只能从每列中选择一个单选按钮。由于表中有4列,因此用户可以从该表中选择4个单选按钮。但我想限制单选按钮的选择。我希望用户只能从该表中选择3个单选按钮。如果用户想要选择数字4,则会有一个警告"你不能选择三个以上。"
这里可以设置限制吗?我该如何设置此限制?
答案 0 :(得分:2)
$("input[type='radio']").change(function(){
var count = $("input[type='radio']:checked").length;
if(count>3){
$(this).prop('checked', false);
alert("You cannot add more than 3");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="radioName1" value="1"> 1 <br>
<input type="radio" name="radioName1" value="2"> 2 <br>
<input type="radio" name="radioName1" value="3"> 3 <br>
<hr>
<input type="radio" name="radioName2" value="1"> 1 <br>
<input type="radio" name="radioName2" value="2"> 2 <br>
<input type="radio" name="radioName2" value="3"> 3 <br>
<hr>
<input type="radio" name="radioName3" value="1"> 1 <br>
<input type="radio" name="radioName3" value="2"> 2 <br>
<input type="radio" name="radioName3" value="3"> 3 <br>
<hr>
<input type="radio" name="radioName4" value="1"> 1 <br>
<input type="radio" name="radioName4" value="2"> 2 <br>
<input type="radio" name="radioName4" value="3"> 3 <br>
答案 1 :(得分:0)
您可以将选定的广播名称存储在一个数组中,并在所选的单选按钮组数量超过3时以编程方式删除最旧的名称。
$(document).ready(function() {
var radioSelected = [];
var numberOfSelected = null;
$('input[type=radio]').change(function() {
numberOfSelected = $('input[type=radio]:checked').length;
var name = $(this)[0].name;
if (radioSelected.indexOf(name) == -1) {
radioSelected.push($(this)[0].name);
}
if(radioSelected.length > 3) {
var removed = radioSelected.shift();
$('input[name=' + removed + ']').prop('checked', false);
}
});
});
.column {
float: left;
margin-right: 40px;
display: flex;
flex-flow: column;
padding: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column">
<div><input type="radio" name="one" value="i" /> i</div>
<div><input type="radio" name="one" value="ii"/> ii</div>
<div><input type="radio" name="one" value="iii"/> iii</div>
</div>
<div class="column">
<div><input type="radio" name="two" /> A</div>
<div><input type="radio" name="two" /> B</div>
<div><input type="radio" name="two" /> C</div>
</div>
<div class="column">
<div><input type="radio" name="three" /> 1</div>
<div><input type="radio" name="three" /> 2</div>
<div><input type="radio" name="three" /> 3</div>
</div>
<div class="column">
<div><input type="radio" name="four" /> a</div>
<div><input type="radio" name="four" /> b</div>
<div><input type="radio" name="four" /> c</div>
</div>