How to get values of checkbox array in Laravel 5? - php

I created checkboxes in form using javascript:
<input type="checkbox" name="is_ok[]" />
<input type="checkbox" name="is_ok[]" />
<input type="checkbox" name="is_ok[]" />
When I check 1st and 3rd checkbox and submit the form, Input::get("is_ok") returns me:
['on', 'on']
Is there any way to get value as ['on', null, 'on'] or ['on', 'off', 'on']?
Thanks in advance.

Hey assign some values to checkboxes like user_id, product_id etc what ever in your application.
E.g. View
<input type="checkbox" name="is_ok[]" value="1" />
<input type="checkbox" name="is_ok[]" value="2" />
<input type="checkbox" name="is_ok[]" value="3" />
E.g. Controller
<?php
if(isset($_POST['is_ok'])){
if (is_array($_POST['is_ok'])) {
foreach($_POST['is_ok'] as $value){
echo $value;
}
} else {
$value = $_POST['is_ok'];
echo $value;
}
}
?>
You will get array of selected checkbox.
Hope it helps..

I think I have a "good" solution to this (kind of).
<input type="checkbox" name="is_ok[0]" />
<input type="checkbox" name="is_ok[1]" />
<input type="checkbox" name="is_ok[2]" />
(Forced indices here)
In the request:
$array = \Request::get("is_ok") + array_fill(0,3,0);
ksort($array);
This will ensure that (a) The checkbox indices are maintained as expected. (b) the gaps are filled when the request is received.
It's sloppy but may work.

IMHO this is the best practice:
In your migration set that db table field to boolean and default 0
$table->boolean->('is_ok')->default(0);
{!! Form::checkbox('is_ok[]', false, isset($model->checkbox) ? : 0) !!}
and if you are not using laravel collective for forms then you can use vanilla php
<input type="checkbox" name="is_ok[]" value="<?php isset($model->checkbox) ? : 0; ?>" />

My solution is this for laravel 5
$request->get('is_ok[]');

Though it might not be best practice, here is what I did first of all I send id of a specific model as a value.
<input type="checkbox" id="verify" name="is_varified[]" value="{{$bank->id}}" {{$bank->is_varified == 1 ? 'checked':''}}>
And in controller I added two query to update the field.
//handaling the issue of checkbox
Bank::where("user_id",$user->id)->whereIn('id',$request->is_varified)->update(['is_varified'=> 1]);
Bank::where("user_id",$user->id)->whereNotIn('id',$request->is_varified)->update(['is_varified'=> 0]);

Related

Multiple Checkboxes array with checked and unchecked values

So i have this line of code that will repeat different times in a form.
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
The !checked show that the checkbox was checked and the !unchecked shows that the checkbox was not checked.
How can i create a php array to get values of checked and unchecked checkboxes in order like this :
array( 0 => checked, 1 => unchecked, 2 => checked, 3 => unchecked );
Momentarily i can get just the checked value with $_POST["checkbox"] but i cannot get the unchecked value.
First of all you need to put a value to your checkboxes:
<input type="checkbox" name="checkbox[]" value="checkboxNchecked" /> !checked
You can't really distinguish your checkboxes otherwise.
Then: Your checkboxes will either return a value if they are checked or will be ignored when they are unchecked. You will not get a NULL, FALSE or other value. It will simply not be transfered via POST/GET to your php script as if it wasn't in yout HTML code. This covers the topic: Does <input type="checkbox" /> only post data if it's checked?
If you know how many checkboxes are around and what they are called - no problemo señor - but if you don't, you'll need to find a way around. If you tell us what the nature of your checkboxes are, we can help you find a tailored solution.
you can use jquery and ajax. In your submit event get all values from the form and submit it by ajax. you can get unchecked value in jquery like this:
$("input:checkbox:not(:checked)")
or
if ($('#idOfYourCheckBox:checked').length > 0) {
//its checked
}
else {
//not checked
}
This will print only checked fields, because unchecked ones are not sent to server.
You will have to do some javascript and hidden field tricks.
Take a look here
Post the checkboxes that are unchecked
<input type="checkbox" name="checkbox[n1]" /> !checked
<input type="checkbox" name="checkbox[n2]" /> !unchecked
<input type="checkbox" name="checkbox[n3]" /> !checked
<input type="checkbox" name="checkbox[n4]" /> !sdsk
foreach($_POST['checkbox'] as $key => $value){
$checkbox[$key] = 'checked';
}
print_r($checkbox); // your new array
Solved:
Declaration of form...
<form id="form1" name="form1" method="post" action="xx.php" onSubmit="set_hidden_value()">
<input name="arrayofchecks" type="hidden" value="toset" />
...
OnSubmit:
function set_hidden_value()
{
var checkstring = "";
for (var i=0; i < $('#checkbox').length; i++)
{
if ($('#checkbox')[i].checked)
{
checkstring = checkstring + "1";
}
else
{
checkstring = checkstring + "0";
}
}
$('#arrayofchecks').val(checkstring);
And the result is a string with values checked and unchecked (1 and 0)...
In my case, i use ajax for intercept submit and do set_hidden_value here...
If you are using a server side language like PHP, there is an easier method than using hidden fields to supply default or writing javascript (both may fail if the user's device/browser doesn't support that method).
<input type="checkbox" value="choice1" name="checkbox[]" />
<input type="checkbox" value="choice2" name="checkbox[]" />
<input type="checkbox" value="choice3" name="checkbox[]" />
This method doesn't return unchecked items, but it specifically identifies which items were checked. Otherwise, if the checkboxes all have the same value, all you get is one, two or 3 values repeated with no idea which item was checked. However, assuming choice2 was checked with the above method, it's pretty easy then to figure out that item 1 and 3 therefore were not checked.
Please check below code.
$("button").click(function () {
var i=0;
var cbox=[];
$("input[name='cbox']").each(function () {
if($(this).is(':checked')) {
cbox[i++] = $(this).val();
}else{
cbox[i++] = "unchecked";
}
});
console.log(cbox);
i = 0;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<button>Click</button>

combine checkbox values using php mysql

I having around 20 check boxes in my form as
<input type="checkbox" name="c1" value="1" />
<input type="checkbox" name="c2" value="2" />
<input type="checkbox" name="c3" value="3" />
<input type="checkbox" name="c4" value="4" />
i would like to these values to a database. I just thought rather than creating 20 fields in my database grab all the values at store in the db as 1,2,3,4 and then when querying to explode the values and display it accordingly using php.
can someone please tell me how am i supposed to concatenate the values 1,2,3,4 from the check fields when submitted so i can pass to the database.
i would appreciate if anyone can suggest a different effective way to achieve this using php.
You can change the name of the checkboxes to be the same, something like
<input type="checkbox" name="cb[]" value="1" />
<input type="checkbox" name="cb[]" value="2" />
Then access them via $_GET or $_POST via
if (isset($_POST['cb'])) {
$my_values = implode(",", $_POST['cb']);
}
If you want them sorted, then you will want to do something like this:
if (isset($_POST['cb'])) {
$my_values = $_POST['cb'];
sort($my_values);
$my_db_value = implode(',', $my_values);
}
For the record, I agree with #Shef in the case that the database can handle the extra load. Depending on when this information will be needed in a highly scalable solution, however, this is a perfectly acceptable way to handle this.
To answer your initial question, first off you need to name your checkboxes all the same name, so:
<input type="checkbox" name="box[]" value="1" />
....
<input type="checkbox" name="box[]" value="20" />
PHP script:
$boxes = $_POST['box'];
$values = implode(",", $boxes); // $values now has "1,2,3,4...", insert into table
A better way would be to have a separate table (see #Shef 's comment).

PHP storing multiple checkbox in database

i did my 'homework' in searching for a solution to this matter through this forum and googling, and ive tried out various ways in solving this, but i can't seem to get the value to be posted into the action file...
i understand the concept of implode / concatenating the array into a string so that it can be stored in the database, i also understand how data are parsed, but i can't seem to get this done..
PHP Form:
<form name="questionnaire_1" action="test_index.php?action=send_questionnaire" method="post">
<table>
<tr class="row-a">
<td>
2. Position<br />
<i>( You may choose more than one option for this question)</i>
</td>
<td colspan="6">
<label> <input type="checkbox" name="position[]" value="1" /> Project Leader (External) </label><br />
<label><input type="checkbox" name="position[]" value="2" /> Project Leader (Internal)
</label><br />
<label><input type="checkbox" name="position[]" value="3" />Project Member (External)
</label> <br />
<label><input type="checkbox" name="position[]" value="4" /> Project Member (Internal)
</label><br />
<label> <input type="checkbox" name="position[]" value="5" />Others (Please Specify)</label>
<input name="position_specify" type="text" size="40" maxlength="40" />
</td>
</tr>
</table>
PHP Action:
if (isset($_POST['Submit']))
{
$position = mysql_prep($_POST['position']);
$allPosition = implode (",", $position);
}
etc ...
the position_specify input has no problem... only having problem with the checkbox... the database takes in varchar(255) for the position.. i really do not know how to solve this..
much help is appreciated, thank you & God bless!
Possible reference to source of mysql_prep() function: http://forums.devnetwork.net/viewtopic.php?f=1&t=81234 . Note that it ends up passing an array to mysql_real_escape_string() which doubtless converts the array to the string "Array", which is then stored in the database. As miki posted in the comments above, imploding before escaping should solve your problem.
You may have a look at bitwise operators. So in otherwords five the first checkbox the value 1 then rhe second value 2 and 3rd value 4. So count in bits. So when submitting the form add all the values together by adding all the values of the checked checkboxes. And then store ome value in the db.
To check if the checkbox was ticked do the following
If($box & 1){ echo 'checkbox 1 is checked';}

Get name and value with PHP

I have this simple form:
HTML:
<input type="checkbox" name="product[]" value="20$" /> book
<input type="checkbox" name="product[]" value="30$" /> plane
PHP:
$product = $_POST['product'];
foreach($product as $value) {
echo $value;
}
Note:
The user can choose one or two ... products.
Question:
I want to know if there is a solution to get the name too, like adding an ID class or something ..
Basically I cant get the name attribute because I didn't sent it with the form.
Add the missing information to your POST-parameters:
<input type="checkbox" name="product[book]" value="20$" /> book
<input type="checkbox" name="product[plane]" value="30$" /> plane
You can iterate over it like this:
foreach ($_POST['product'] as $name => $value) {
// ...
}
You can use the option presented by elusive, but it seems that in this case you're passing the price from the client to the server. That might allow people to fraud. They could with only a little hacking send another (lower) price. If you just send 'book' and redetermine the price on the server, this won't be a problem.
If you choose that path, you can just put the product ('book') in the value:
<input type="checkbox" id="book" name="product[]" value="book" />
<label for="book">book</label>
<input type="checkbox" id="plane" name="product[]" value="plane" />
<label for="plane">plane</label>

determine whether checkbox is checked php $_GET

I just want to have php determines whether a checkbox is checked, but I am running into a problem of getting the right return. Help please.
My html code
<label>
<input name="Language" type="checkbox" id="aa" checked="checked" />
One</label>
<label>
<input name="Language" type="checkbox" id="bb" />Two</label>
<label>
<input type="checkbox" name="Language" id="cc" />Three</label>
I pass the values to php by the $_GET method
my php code:
$aa=$_GET["aa"];
$bb=$_GET["bb"];
$cc=$_GET["cc"];
echo $aa."<br>";
echo $bb."<br>";
echo $cc."<br>";
the output is
true
false
false
I next want to just determine if each box is checked and if so, do something.
if ($aa == true) { $abc="checked";}
else { $abc="not checked"; }
if ($bb == true) { $cde="checked";}
else { $cde="not checked"; }
if ($fgh == true) { $fgh="checked";}
else { $fgh="not checked"; }
But the if statements always return true, even if the box is not checked. I tried variations of "===" and "!=", but it does not seem to work.
TIA
if (isset($_GET['checkbox_name'])) { ... }
Form controls (with the exception of file inputs, and with some special rules for image inputs) always submit strings. There is no concept of a boolean in a query string or a form encoded POST body.
The id is irrelevant — only the name and value matter (at least as far as PHP is concerned).
Since you haven't given them values they will, IIRC, default to on so if you are doing a comparison you should look for that. Looking with isset is simpler though. This is somewhat beside the point though, since your example gives them all the same name and value, so you can't differentiate between them.
Additionally, due to an oddity of the PHP form data parser, you have to end the with [] if you want multiple elements with the same name.
You probably want to do something like this:
<label>
<input name="Language[]" type="checkbox" id="aa" checked="checked" value="One" />
One</label>
<label>
<input name="Language[]" type="checkbox" id="bb" value="Two" />Two</label>
<label>
<input type="checkbox" name="Language[]" id="cc" value="Three" />Three</label>
Important: Note the addition of values and the change in name.
Then in PHP $_GET['Language'] will be an Array of the values of the checked checkboxes, which you can loop over.
Try isset()
I think your HTML code should be like
<label>
<input name="Language[]" type="checkbox" id="aa" checked="checked" value ="1" />One
</label>
<label>
<input name="Language[]" type="checkbox" id="bb" value ="2" />Two
</label>
<label>
<input name="Language[]" type="checkbox" id="cc" value ="3" />Three
</label>
and then by using something like
$count = count($_GET["Language"]); you can count the number of checkboxes checked.
Or do
$arr = $_GET["Language"]; //$arr is an array that contains the values of the checked checkboxes
Then you can foreach over the array
foreach( $arr as $item)
{
echo $item . "</br>"; /* Will print 1,2 and 3 (mind newlines)*/
}
In my PHP I got it from $_POST['checkbox_name'], and I found that the variable had the value on when the box was checked (i.e. it existed even if the checkbox was clear).

Categories