Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Input type="checkbox" value=0 showing error (NULL)

Toggles Image

I have designed the checkbox like this, If checkbox is checked then the input value will be 1 else it’ll be 0

I have added logic with javascript

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    <script>
        $('#exams, #materials, #notes, #course_live,, #schedule').on(
            'change',
            function() {
                this.value = this.checked ? '1' : '0';
            }).change();
    </script>

Now when I submit the form if the checkbox is checked it’s working perfect, but if the checkbox is not checked it showing error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'exams' cannot be null

But I want this that if the checkbox is not checked then the value should be 0, And it’s showing perfectly in Inspect, I have removed the validation from laravel but showing the same. Please help me out.

>Solution :

3 Ways :

1st: Conditional set in PHP

empty($request->input('your_input')) ? 0 : 1 ;

2nd: Set Database default to 0 (DB will convert null values to 0 automatically)

3rd: HTML trick: as Marwelln answer: you can put a hidden input before your checkbox with a default value.

<input type='hidden' name='foobar' value='0' /> <!-- default value if foobar checkbox is not checked -->
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading