How to set value of checkbox when checked and unchecked using ajax or jquery

前提是你 提交于 2020-01-25 11:29:07

问题


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

回答1:


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



回答2:


The value of a checkbox never changes (by itself). If the checkbox is not checked its value simply won't be sent to the server. So at the server side you should check whether one_by_one is included in the request and set the value accordingly (e.g. set 0 if it doesn't exist or the value of one_by_one if it does).



来源:https://stackoverflow.com/questions/26220352/how-to-set-value-of-checkbox-when-checked-and-unchecked-using-ajax-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!