I am trying to see if a checkbox is checked or not in my controller. I've read that this is the code to do it
if (Input::get('attending_lan', true))
But that returns true even if the checkbox is unchecked.
prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.
We can use the isset() function to check whether the checkbox is checked in PHP. The isset() function takes the $_POST array as argument. The $_POST array contains the specific value of the name attribute present in HTML form. For example, create a form in HTML with POST method and specify the action to index.
How do you pass checkbox value 0 if not checked and 1 if checked? Add a hidden input that has the same name as the checkbox with the value of 0 BEFORE the checkbox. If the checkbox is unchecked, the hidden field value will be used, if it is checked the checkbox value will be used.
Use Input::has('attending_lan')
Generally speaking, if the checkbox is checked, the request variable will exist. If that is not the case you have a problem somewhere else in the code.
Also relavant: Does <input type="checkbox" /> only post data if it's checked?
Assuming you have this form code in your view:
// view.blade.php
{{ Form::open() }}
{{ Form::checkbox('attending_lan', 'yes') }}
{{ Form::submit('Send') }}
{{ Form::close() }}
You can get the value of the checkbox like this:
if (Input::get('attending_lan') === 'yes') {
// checked
} else {
// unchecked
}
The key here is that you have to set a value when creating the checkbox in your view (in the example, value would be yes
), and then check for that value in your controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With