0

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
8
  • How are you saving it to your database? Commented Oct 6, 2014 at 16:15
  • @j08691 I was using an html form in codeigniter. So when i press save button the data will be saved in the mysql database. Commented Oct 6, 2014 at 16:16
  • @FelixKling I see. How can i do that in the server side? Commented Oct 6, 2014 at 16:17
  • Probably something like $value = isset($_POST['one_by_one']) ? 1 : 0;. If you are using codeigniter than it might provide helper functions for accessing the data of a request. Commented Oct 6, 2014 at 16:19
  • @FelixKling Is there a way to set it on client side? Jquery perhaps? Commented Oct 6, 2014 at 16:23

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply. Does this works for multiple checkboxes?
Hi. I've tried your code but the value being saved in database is still 1.
Searched for the solution over the stack. And finalized here!!! Thanks a million.
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).

2 Comments

Thanks for your reply. How can i set the value accordingly on php? Can you give me some snippet?
Probably something like $value = isset($_POST['one_by_one']) ? 1 : 0;.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.