【发布时间】:2019-07-11 13:27:19
【问题描述】:
我有一个带有单选框列(“是”/“否”)的表格。
挑战在于创建一个按钮,将所有单选框切换为“是”或“否”,具体取决于单击时它们具有的值。
如何将不同组的单选框相互连接?
我以前做过类似的任务,但有复选框。有了它们,您只需在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);
}
})
})
但是当你只有一两篇文章,然后多次按下“选择/取消选择”按钮时,会有一个错误。 出现这种单选框行为的原因可能是什么? 有人知道如何处理单选按钮吗?
【问题讨论】:
-
您不应拒绝编辑,获取其内容,然后应用您的编辑。以后,接受修改(只要它没有破坏性或违反任何规则),然后应用您的修改。
-
对不起,我对 StackOverflow 还是很陌生,也许编辑被意外拒绝了,你能再做一次吗?非常抱歉;(
-
别担心,我们都得学点什么。
标签: javascript html