复选框值0或1

时间:2013-08-18 04:52:54

标签: javascript jquery html css

在很多情况下,我有以下复选框

 <input type="checkbox" name="custom7" value="1" id="custom7"
 checked="checked"> <label for="custom7">Email me more info?</label>

现在选中复选框时,值应为1,如值= 1。如果取消选中该复选框,我希望该值为零,如值= 0。我怎样才能做到这一点?

7 个答案:

答案 0 :(得分:12)

只是做个屁股并提供稍微简短的回答:

$('input[type="checkbox"]').change(function(){
    this.value = (Number(this.checked));
});

答案 1 :(得分:8)

谢谢你的工作

$('#custom7').on('change', function(){
   this.value = this.checked ? 1 : 0;
   // alert(this.value);
}).change();

link:http://jsfiddle.net/WhQaR/

答案 2 :(得分:5)

不要忘记bitwise XOR运算符:

$('input[type="checkbox"]').on('change', function(){
    this.value ^= 1;
});

$('input[type="checkbox"]').on('change', function(){
    this.value ^= 1;
    console.log( this.value )
});
<label><input type="checkbox" name="accept" value="1" checked> I accept </label>
<label><input type="checkbox" name="accept" value="0"> Unchecked example</label>

<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>

答案 3 :(得分:2)

你不能先尝试google吗?试试这个。

$('#custom7').change(function(){
     $(this).val($(this).attr('checked') ? '1' : '0');
});

答案 4 :(得分:2)

没有太大意义,因为未注释的复选框不会像评论中所述那样发送到服务器,但如果您需要服务器中的值,则可以使用隐藏字段:

<强> HTML:

<input type="checkbox" value="1" id="custom7" checked="checked" /> 
<input type="hidden" value="1" id="hdncustom7" name="custom7" />
<label for="custom7">Email me more info?</label>

<强> jQuery的:

$('#custom7').on('change', function(){
   $('#hdncustom7').val(this.checked ? 1 : 0);
});

使用此方法,您将在服务器

中收到{0}或0或1的custom7

答案 5 :(得分:0)

非常简单的方法

<input type="hidden" name="is_active" value="0" />
<input type="checkbox" name="is_active" value="1" />

更改全局复选框的行为方式

document.addEventListener('DOMContentLoaded', e => {
for (let checkbox of document.querySelectorAll('input[type=checkbox]')) {
    checkbox.value = checkbox.checked ? 1 : 0;
    checkbox.addEventListener('change', e => {
            e.target.value = e.target.checked ? 1 : 0;
       });
    }
});

答案 6 :(得分:-1)

此代码对我有用。

jQuery:

$('#custom7').on('change', function(){ var custom=$("#custom7").is(':checked')?1:0; }

相关问题