我有一个带有单选框列("is"/“否”)的表格。
挑战在于创建一个按钮,根据单击时它们的值将所有单选框切换为"is"或“否”。
如何将不同组的单选框相互连接起来?
我以前做过类似的任务,但有复选框。有了它们,您只需在 checked, true
和 checked, false
之间切换。
我遇到了这个答案:Jquery function to toggle all radio buttons on the page as但是他们有两个按钮,而我只有一个。
这是我的代码示例:
$('.select-deselect-all').on('click', function() {
var radios = $('tbody.table-body').find('input[type=radio]')
$(radios).each(function() {
$(this).hasClass('checked') ? $(this).prop('checked', true) : $(this).prop('checked', false)
})
<button type="button" class="btn select-deselect-all">
Select/deselect all
</button>
<br>
<table id="articles_table" class="table no-highlight">
<thead>
<tr>
<th>Article number</th>
<th>Description</th>
<th>Commodity code</th>
<th class="table-radio-column">Request Supplier Declaration?</th>
</tr>
</thead>
<tbody class="table-body">
<tr>
<td class="article-number">1</td>
<td>2</td>
<td>3</td>
<td class="table-radio-column">
<div>
<input type="radio" id="1_YES" class="request-article-choice" name="1" value="Yes" checked>
<label for='1_YES'>Yes</label>
<input type="radio" id="1_NO" class="request-article-choice ml-20" name="1" value="No">
<label for='1_NO' class="ml-20">No</label>
</div>
</td>
</tr>
<tr>
<td class="article-number">1</td>
<td>2</td>
<td>3</td>
<td class="table-radio-column">
<div>
<input type="radio" id="2_YES" class="request-article-choice" name="2" value="Yes" checked>
<label for='2_YES'>Yes</label>
<input type="radio" id="2_NO" class="request-article-choice ml-20" name="2" value="No">
<label for='2_NO' class="ml-20">No</label>
</div>
</td>
</tr>
<tr>
<td class="article-number">1</td>
<td>2</td>
<td>3</td>
<td class="table-radio-column">
<div>
<input type="radio" id="3_YES" class="request-article-choice" name="3" value="Yes" checked>
<label for='3_YES'>Yes</label>
<input type="radio" id="3_NO" class="request-article-choice ml-20" name="3" value="No">
<label for='3_NO' class="ml-20">No</label>
</div>
</td>
</tr>
</tbody>
</table>
更新
它与以下代码一起正常工作:
$('.select-deselect-all').on('click', function() {
$('td input[type=radio]').each(function() {
if($(this).prop('checked') || $(this).attr('checked')) {
$(this).prop('checked', false);
$(this).attr('checked', false);
} else {
$(this).prop('checked', true);
$(this).attr('checked', true);
}
})
})
但是当您只有一两篇文章然后多次按下“选择/取消选择”按钮时会出现错误。 出现这种单选框行为的原因可能是什么? 有人知道如何处理单选按钮吗?
最佳答案
我找到了这个问题的解决方案(这个函数在彼此之间切换 2 个单选按钮组):
$('.select-deselect-all').on('click', function() {
var radio = $('input[type="radio"]:checked').first().val();
$('input[type="radio"]').each(function() {
if ($(this).val() !== radio) {
$(this).click();
}
});
});
关于javascript - 如何在单击按钮时切换所有单选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56990349/