Multiple Checkboxes array with checked and unchecked values - php

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>

Related

Posting array of checkboxes in PHP

I have multiple checkboxes with names of adminMeta[], such as:
<input type="checkbox" name="adminMeta[name1]" value="1" />
<input type="checkbox" name="adminMeta[name2]" value="1" />
and so on and I also have text inputs like this too with the same names.
When the data is posted, I am looping through using a foreach loop:
foreach($_POST["adminMeta"] as $a => $b) {
}
inside the loop, I add/update the record in my database depending on whether it exists already or not.
But I am having some issues with checkboxes and knowing whether they are checked or not.
I have tried using if(isset($b)) but that hasn't worked.
How can I tell inside my loop, whether a checkbox is checked or not?
If a checkbox is not checked, then it is not a successful control.
If it is not a successful control, then it won't be included in the form data at all.
If it isn't in the form data, then it won't appear when you loop over the form data.
So
If it is in the form data, then it is checked
Otherwise it is not checked
Normally I'd approach this problem with something along the lines of:
$list_of_checkboxes = [ "name1", "name2" ];
Then generate the form with:
foreach ($list_of_checkboxes as $name) {
?>
<label>
<input type="checkbox"
name="adminMeta[]"
value="<?php echo htmlspecialchars($name); ?>">
<?php echo htmlspecialchars($name); ?>
</label>
<?php
}
Then test the data with:
foreach ($list_of_checkboxes as $name) {
if (in_array($name, $_POST['adminMeta'])) {
# Checked
} else {
# Not checked
}
}
Another approach would be to set hidden inputs before each check with default value of 0:
<input type="hidden" name="adminMeta[name1]" value="0" />
<input type="checkbox" name="adminMeta[name1]" value="1" />
<input type="hidden" name="adminMeta[name2]" value="0" />
<input type="checkbox" name="adminMeta[name2]" value="1" />
Now you will receive the data even if you don't check the checkboxes.

Make checkbox return false when unchecked

I have a form looking like:
<form>
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
</form>
The number of checkboxes will variate from time to time so when processing this data with PHP I have to loop the _POST['checked'] array.
My problem is that I want to take actions both when a checkbox is checked and when it's not. But only the the checked checkboxes will be added to the _POST['checked'] array.
<form>
<input type="checkbox" key="1"/>
<input type="hidden" name="checked[1]" value="false">
<input type="checkbox" key="2"/>
<input type="hidden" name="checked[2]" value="false">
<input type="checkbox" key="3"/>
<input type="hidden" name="checked[3]" value="false">
<input type="checkbox" key="4"/>
<input type="hidden" name="checked[4]" value="false">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('[key]').change(function () {
var key = $(this).attr('key');
$($('[name="checked[' + key + ']"]')).val($(this).is(':checked') ? 'true' : 'false');
});
});
</script>
here is what i'm doing
i'm using two inputs one is checkbox without name so it won't be sent to php
, the other is hidden won't be shown to the user but it is what will be sent to php
then with jquery when the user check the box jquery change the value of the hidden input to true and when uncheck it change the value to false
so the value will always be send to the php with value true or false as string
you can change the value you want to send to php by changing this
.is(':checked')?'true':'false')
to something like that .is(':checked')?1:0) to send 1 and 0 instead of true and false
another solution is rybo111 solution
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">
it will send the two options but if the checkbox is checked it will override the first option
but it is not reliable 100% and it will send more data to the server
read more about that in POSTing Form Fields with same Name Attribute
so if you want to use simple solution without js use the "html only"
if you want 100% reliable solution use the "js"
Here's a technique I've seen before:
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">
The reason this works is because when values with the same name are sent more than once, only the last value is accepted.
In my opinion, a better way is to simply use isset($_POST['...']) or in_array($_POST['...']).
Add value="true" to each checkbox input element.
And change your PHP code to :
$checked_arr = [];
foreach($_POST["checked"] as $checked){
if($checked == "true"){
// do what you want to do
}
}
Another Solution is server-side solution that I think is too fast and easy.
client side:
Just use fresh HTML :
<input type="checkbox" name="checked1" value="value_checked" ... />
server side:
make global function like this:
function getVal(&$var, $default = '') {
if (!isset($var) || empty($var) || is_null($var))
$var = $default;
return $var;
}
then use where you want to read some value that you don't know is set or not.
like this:
$checked_value = getVal($_POST["checked1"],false);
or
$checked_value = getVal($_POST["checked1"],"value_not_checked");
I hope useful to another one.
This is best approach according to my experience
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">

How to check Checkbox not checked in foreach

I have html checkbox like this:
<form action="" method="post">
<input type="checkbox" name="language[]" value="php" />PHP<br />
<input type="checkbox" name="language[]" value="html" />HTML<br />
<input type="checkbox" name="language[]" value="java" />Java<br />
<input type="checkbox" name="language[]" value="c++" />C++<br />
<input type="submit" value="send" />
</form>
Now I want to detect the checkbox is not checked using this PHP
if($_POST)
{
if(empty($_POST['language']))
{
echo "bla";
}
else
{
foreach($_POST['language'] as $value)
{
echo 'Checked: '.$value.'
';
}
}
}
The output is always show the checbox checked.
My question is, how can I detect the checkbox is not checked?
Example I do not check PHP and Java.
You don't need to validate checkbox by checkbox in order to determine if they are checked or not, you won't get the unchecked checkboxes values at the time you send the form, so, sending the form like this:
<form action="" method="post">
<input type="checkbox" name="language[]" value="php" />PHP<br /> <!-- checked -->
<input type="checkbox" name="language[]" value="html" />HTML<br /><!-- checked -->
<input type="checkbox" name="language[]" value="java" />Java<br /><!-- unchecked -->
<input type="checkbox" name="language[]" value="c++" />C++<br /><!-- unchecked -->
<input type="submit" value="send" />
</form>
In your PHP, you will get an array as follows:
$_POST['languages'] = array("php", "html");
Now, lets say you have an array of all the values in order to check which ones you need to delete, and which ones you need to add, a rough code example would be as follows:
$allValues = array('php', 'html', 'java', 'c++');
$valuesForAdd = $_POST['language'];
$valuesForDeletion = array_diff($allValues, $valuesForAdd);
First you need the selectable items array in the backend:
$items = array('php','html','java','c++');
You have the posted (selected) languages array here:
$_POST['language']
Not selected languages array:
$not_selected_languages = array_diff($items,$_POST['language']);
I hope it helps.
Only 'checked' checkboxes get sent as parameters in a POST request.
If you want to know which aren't checked, you could have the value list stored on PHP side; then once you receive POST data - compare the array on PHP side with POST array.
$all_vals = array('php', 'c++', 'html', 'java');
$post_vals = $_POST['languages'];
foreach ($post_vals as $post_val)
if in_array($post_val, $all_vals)
$checkbox checked
else
$checkbox not checked
I assume this gives you enough liberty to do what you need.

PHP/Javascript limiting amount of checkboxes

Im trying to limit the amount of checkboxes that can be checked, in this case only 3 can be checked. When using plain HTML this works fine. The code can be seen below.
HTML example
<td ><input type=checkbox name=ckb value=2 onclick='chkcontrol()';></td><td>Perl</td>
Javascript Function
<script type="text/javascript">
function chkcontrol(j) {
var total=0;
for(var i=0; i < document.form1.ckb.length; i++){
if(document.form1.ckb[i].checked){
total =total +1;}
if(total > 3){
alert("Please Select only three")
document.form1.ckb[j].checked = false;
return false;
}
}
}
</script>
The problem appears when replacing the fixed HTML values with values from a MYSQL database. All the information appears correctly, and can be posted to another page via a submit button. However, it seems like the 'value' assigned to each record from the database is not making its way too the javascript function.
<td><input name="checkbox[]" type="checkbox" value="<?php echo $rows['TCA_QID'];?>" onclick="chkcontrol();"></td>
I have tried changed the name in the javascript function to match the 'checkbox' name.Any advice would be greatly appreciated
Thanks
In the second version, your input element's name is "checkbox[]", but in your JavaScript function you're looking for an element with a name of ckb. The JavaScript function cannot find your field if you're telling it to look for the wrong name.
You say you've tried changing this. What happened when you tried that? Make sure you're naming the element "ckb", not "ckb[]".
Have you looked at what the checkboxes' values are in the generated HTML for the page? Do they match what you expect?
<script type="text/javascript">
<!--
//initial checkCount of zero
var checkCount=0
//maximum number of allowed checked boxes
var maxChecks=3
function setChecks(obj){
//increment/decrement checkCount
if(obj.checked){
checkCount=checkCount+1
}else{
checkCount=checkCount-1
}
//if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert
if (checkCount>maxChecks){
obj.checked=false
checkCount=checkCount-1
alert('you may only choose up to '+maxChecks+' options')
}
}
//-->
</script>
</head>
<body>
<form>
Option1 <input type="checkbox" id="check1" onclick="setChecks(this)"><br />
Option2 <input type="checkbox" id="check2" onclick="setChecks(this)"><br />
Option3 <input type="checkbox" id="check3" onclick="setChecks(this)"><br />
Option4 <input type="checkbox" id="check4" onclick="setChecks(this)"><br />
Option5 <input type="checkbox" id="check5" onclick="setChecks(this)"><br />
Option6 <input type="checkbox" id="check6" onclick="setChecks(this)"><br />
</form>
</body>

Jquery array validation + php

I have a checkbox group in my html form.The check box group contains array.
My question is how validate the checkbox array using jquery and get the array value in php
The code given below
<input type="checkbox" name="go[]" value="1" /><label>Married</label><br>
<input type="checkbox" name="go[]" value="2" /><label>Widowed</label><br>
<input type="checkbox" name="go[]" value="3" /><label>Single</label><br>
<input type="checkbox" name="go[]" value="4"/><label>Minor</label>
Thanks in advance.
I think you're trying to use the jQuery Validation plugin to make sure that at least one checkbox from your group is checked.
The Validation plugin doesn't like input names with brackets in them. Try this in your form's validate method:
rules: {
'go[]': { //since it has brackets, the name must be in quotes to work
required: true,
minlength: 1
}
If you mean how to validate check boxes because they contain [], here is one solution using ids instead:
<script type="text/javascript">
function validate()
{
var proceed = true;
for(var i = 1; i <= 4; i++)
{
if (!$("#" + i).is(':checked'))
{
proceed = false;
break;
}
}
if (proceed == true)
{
return true;
}
else
{
alert('All Fields Are Required !!');
return false;
}
}
</script>
And the html form might look like this:
<form action="frm" method="post" onsubmit="return validate();">
<input type="checkbox" id="1" name="go[]" value="1" /><label>Married</label><br>
<input type="checkbox" id="2" name="go[]" value="2" /><label>Widowed</label><br>
<input type="checkbox" id="3" name="go[]" value="3" /><label>Single</label><br>
<input type="checkbox" id="4" name="go[]" value="4"/><label>Minor</label>
<br />
<input type="submit">
</form>
For PHP:
// get checkboxes array
$chk_array = $_POST['go'];
Now you can manipulate $chk_array array in any way you want:
Note:
$chk_array[0] // contains your 1st checkbox value
$chk_array[1] // contains your 2nd checkbox value
$chk_array[2] // contains your 3rd checkbox value
$chk_array[3] // contains your 4th checkbox value
In php, arrays start from 0 index.
Thanks

Categories