如何在单击时切换单选输入元素的检查状态
How to toggle the check state of a radio input element on click?
如何在单击元素或其容器时(取消)检查单选输入元素?
我试过下面的代码,但它没有取消选中收音机。
HTML:
<div class="is">
<label><input type="radio" name="check" class="il-radio" /> Is </label>
<img src="picture" />
</div>
jQuery:
$(".is label, .is ").click(function () {
if (!$(this).find(".il-radio").attr("checked")) {
$(this).find(".il-radio").attr("checked", "checked");
} else if ($(this).find(".il-radio").attr("checked") == "checked") {
$(this).find(".il-radio").removeAttr("checked");
}
});
您必须防止默认行为。目前,点击后,会发生以下情况:
- 为容器(
div.is
)激发click
事件 - 为标签激发
click
事件 - 由于您的函数切换一个状态,并且事件侦听器被调用两次,因此结果是似乎什么都没有发生
已更正代码(http://jsfiddle.net/nHvsf/3/):
$(".is").click(function(event) {
var radio_selector = 'input[type="radio"]',
$radio;
// Ignore the event when the radio input is clicked.
if (!$(event.target).is(radio_selector)) {
$radio = $(this).find(radio_selector);
// Prevent the event to be triggered
// on another element, for the same click
event.stopImmediatePropagation();
// We manually check the box, so prevent default
event.preventDefault();
$radio.prop('checked', !$radio.is(':checked'));
}
});
$(".il-radio").on('change click', function(event) {
// The change event only fires when the checkbox state changes
// The click event always fires
// When the radio is already checked, this event will fire only once,
// resulting in an unchecked checkbox.
// When the radio is not checked already, this event fires twice
// so that the state does not change
this.checked = !this.checked;
});
单选按钮不取消选中,您需要使用复选框(type='checkbox')
只使用html,相同的功能
<label for="rdio"><input type="radio" name="rdio" id="rdio" class="il-radio" /> Is </label>
相关文章:
- Javascript获取具有不同id的文件数's来自没有多个属性的文件输入元素
- 访问代码生成的输入元素上的keyup事件
- 如何通过jQuery发送选定的元素和文本输入
- 使用 jQuery,当我在输入框外部单击时,如何更改输入元素的值
- 从IE中的不同元素调用时,文件输入控件未正确启动
- 使用jQuery切换来显示内容,但防止在用户单击输入元素时关闭
- 单击其他元素或鼠标向上时隐藏输入框,但保留一次焦点
- 如何在dom元素中插入输入标记数据插件
- 根据输入文本按元素排序,AngularJS
- 更新最大滑块元素输入类型=文本
- 角度/动画引导元素(输入组)
- 如何创建表单元素输入框,标签使用javascript onclick
- 绑定到单击事件以查找子元素输入值
- 特定值元素输入未被读取
- 在JavaScript中将用户输入的元素输入到数组中
- JQuery隐藏元素输入问题遍历
- 如何找出表单是否没有任何元素(输入,选择)在jquery
- 使用表单元素(输入)初始化放大弹出菜单
- 如何获取所有子元素输入
- 基于子元素输入控制父元素:focus