[英]input type radio button checked else statement not working in jquery
我想在单选按钮的父包装中添加一个类,我这样做了,它正在工作但是否则语句不起作用
这是我的代码
<div class="radio">
<input type="radio" name="name[]" checked>
</div>
<div class="radio">
<input type="radio" name="name[]">
</div>
这是我的JS
$(document).ready(function(){
$('input[type="radio"]').on('click',function(){
if($(this).prop('checked')){
$(this).parent().addClass('new')
}
else {
$(this).parent().removeClass('new')
}
});
})
我想在未选中单选按钮时删除新类,但它不起作用。 例如http://codepen.io/amitabha197/pen/KzqvWv
在webeno和mhodges向我指出正确的方向后,这是我的解决方案。
$('input[type="radio"]').on('change',function(){
$(this).parent().addClass('new').siblings().removeClass('new');
});
还要注意记住,如果你一直试图取消选中一个单选按钮,那就知道了。
您无法取消选中单选按钮 。 您对其执行的所有点击都会对其进行检查, 而是使用复选框。
用于代码优化和模块化。
$(document).ready(function(){
$('input[type="radio"]').on('click',function(){
var name = $(this).attr("name");
$('input[type="radio"][name="'+name+'"]').closest(".radio").removeClass("new");
$(this).closest(".radio").addClass("new");
});
});
使用此功能将解决您的问题
$(document).ready(function(){
$('input[type="radio"]').on('change',function(){
$(this).parent().addClass('new');
$('input[type="radio"]').not(this).parent().removeClass('new');
});
});
您可以在html
包含<label>
元素作为<input type="radio">
元素的父元素。
HTML标签元素 (
<label>
)表示用户界面中项目的标题。 它可以通过将控件元素放在<label>
元素内,或者使用for属性与控件关联。 这种控制称为标签元素的标记控制 。 一个输入可以与多个标签相关联。
父label
元素将与:checked
第一个子后代input
相关联。
您可以设置css
样式:after
伪元素复合到:checked
选择器以在input
元素为:checked
时显示蓝色border
。
div.radio { display: inline-block; } label.radio { display: inline-block; width: 100px; border: 1px solid #000; } label.radio > :checked:after { content: ""; position: relative; display: inline-block; width: 100px; height: 20px; left: -6px; top: -4px; border: 1px solid blue; }
<div class="radio"> <label class="radio"> <input type="radio" id="radio1" name="name[]" checked> </label> </div> <div class="radio"> <label class="radio"> <input type="radio" for="radio2" name="name[]"> </label> </div>
如果要求是利用现有html
, jQuery
,你可以利用.click()
.toggleCLass()
来添加,删除"new"
className
如果后代input
元素checked
属性是false
的click
事件,设定input
checked
属性为true
$(document).ready(function() { var radio = $(".radio"); radio.click(function(e) { var input = e.target.querySelector("input[type=radio]"); if (!input.checked) { radio.toggleClass("new"); input.checked = true; } }) })
.radio { display: inline-block; width: 100px; border: 1px solid #000; } .new { display: inline-block; width: 100px; border: 1px solid blue !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div class="radio new"> <input type="radio" name="name[]" checked> </div> <div class="radio"> <input type="radio" name="name[]"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.