【问题标题】:Input checked changes button class输入检查更改按钮类
【发布时间】:2015-09-20 04:17:27
【问题描述】:
希望从按钮中删除禁用类并在选中单选按钮以及选中 1 个或多个复选框时添加启用类。
<div>
<input name="select-customer" type="radio">btn 1
<input name="select-customer" type="radio">btn 2
</div>
<div>
<input type="checkbox" name="choice-selection">Choice 1
<input type="checkbox" name="choice-selection">Choice 2
<input type="checkbox" name="choice-selection">Choice 3
<input type="checkbox" name="choice-selection">Choice 4
</div>
https://jsfiddle.net/dLyvo7d0/
【问题讨论】:
标签:
javascript
css
checkbox
input
radio-button
【解决方案1】:
if( $( "input[name='select-customer']" ).is(':checked')) {
if( $( "input[name='choice-selection']" ).is(':checked')){
$('#btn').prop('disabled', 'disabled');
} else {
$('#btn').prop('disabled', false);
}
}
}
试试这个
【解决方案2】:
这是一个纯 JavaScript 函数,它监听点击事件,然后根据输入的点击状态更改按钮的类:
document.body.addEventListener('click', function() {
if(document.querySelector('[name="select-customer"]:checked') ||
document.querySelector('[name="choice-selection"]:checked')
) {
document.querySelector('button').className= 'enable';
}
else {
document.querySelector('button').className= 'disable';
}
});
.disable {
background: gray;
}
.enable {
background: green;
}
<div>
<input name="select-customer" type="radio">btn 1
<input name="select-customer" type="radio">btn 2
</div>
<div>
<input type="checkbox" name="choice-selection">Choice 1
<input type="checkbox" name="choice-selection">Choice 2
<input type="checkbox" name="choice-selection">Choice 3
<input type="checkbox" name="choice-selection">Choice 4
</div>
<button class="disable">Button</button>
【解决方案3】:
$(document).ready(function(){
$('#button').click(function(){
$('input:radio').each(function () {
var $this = $(this);
if (($this).prop('checked')) {
$this.closest('span').addClass('enable');
$this.closest('span').removeClass('disable');
}else{
$this.closest('span').addClass('disable');
$this.closest('span').removeClass('enable');
}
});
$('input:checkbox').each(function () {
var $this = $(this);
if (($this).prop('checked')) {
$this.closest('span').addClass('enable');
$this.closest('span').removeClass('disable');
}else{
$this.closest('span').addClass('disable');
$this.closest('span').removeClass('enable');
}
});
});
});
.disable {
background: gray;
}
.enable {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span><input name="select-customer" type="radio"/>btn 1</span>
<span><input name="select-customer" type="radio"/>btn 2</span>
</div>
<div>
<span><input type="checkbox" name="choice-selection"/>Choice 1</span>
<span><input type="checkbox" name="choice-selection"/>Choice 2</span>
<span><input type="checkbox" name="choice-selection"/>Choice 3</span>
<span><input type="checkbox" name="choice-selection"/>Choice 4</span>
</div>
<button class="disable" id="button">Button</button>