如何在使用ajax或jquery选中和取消选中时设置复选框的值 [英] How to set value of checkbox when checked and unchecked using ajax or jquery

查看:126
本文介绍了如何在使用ajax或jquery选中和取消选中时设置复选框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选中和取消选中时,我需要获取复选框的值,并将其保存在数据库中。如果选中,则值为1,如果未选中则值为0。我目前正在使用下面的代码段,它显示我想要的结果,当我提醒它。但是,保存在数据库中时会出现问题。它仍然获得我在复选框E.G中设置的值:value ='1'。



这是我的jQuery代码:

  $(document)。 ready(function(){
$('input [type =checkbox]')。click(function(){
var val = this.type ==checkbox?+ this.checked :this.value;
});
});

这是我的HTML复选框:

< input type =checkboxvalue =1name =one_by_oneid =one_by_oneclass =one_by_one> One 

解决方案

div class =snippetdata-lang =jsdata-hide =false>

 < $(this).val(1):$($)$(this).prop(checked)$($)$('input [type =checkbox (this).val(0)});  

< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< input type =checkboxvalue = 1name =one_by_oneid =one_by_oneclass =one_by_one>一个

b

I need to get the value of the checkboxes when checked and unchecked and save it in database. The value is 1 if checked and 0 if unchecked, respectively. I am currently using the snippet below and it show the result i want when i alert it. But the problem comes when saving in the database. It still gets the value I have set in my checkbox E.G: value='1'.

Here is my jQuery code:

$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
        var val = this.type == "checkbox" ? +this.checked : this.value ;            
    });
});

Here is my HTML checkbox:

<input type="checkbox" value="1" name="one_by_one" id="one_by_one" class="one_by_one">One

解决方案

Probably you want this:

$('input[type="checkbox"]').click(function () {
    $(this).prop("checked") ? $(this).val("1") : $(this).val("0")
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" name="one_by_one" id="one_by_one" class="one_by_one">One

这篇关于如何在使用ajax或jquery选中和取消选中时设置复选框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆