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

Time:09-21

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

    <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.

CodePudding user response:

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 -->

CodePudding user response:

When an html input type with checkbox is not checked it will not exist in the post array. To solve this you can put a hidden input before you checkbox with a default value.

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

If you use this method you can remove your javascript change trigger as it's not needed.

CodePudding user response:

Best practice to follow is to check if your checkboz is present in request or not Using

$request->has('key')

CodePudding user response:

If the checkbox isn't checked, then it won't be a successful control, and its value will not be included in the submitted data. Giving it a different value when it isn't checked is pointless.

Handle this server-side instead. For example:

<form method="post">
<input name="toggle[]" value="exams" type="checkbox">
<input name="toggle[]" value="materials" type="checkbox">
<input name="toggle[]" value="notes" type="checkbox">
<input name="toggle[]" value="course_live" type="checkbox">
<input name="toggle[]" value="schedule" type="checkbox">
<button>Submit</button>
</form>

<?php

$toggle = [
    "exams" => 0,
    "materials" => 0,
    "notes" => 0,
    "course_live" => 0,
    "schedule" => 0,
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($toggle as $key => $value) {
        if (in_array($key, $_POST['toggle'])) {
            $toggle[$key] = 1;
        }
    }

    ?><pre><?php
        echo json_encode($toggle,  JSON_PRETTY_PRINT);
    ?></pre><?php
}
  • Related