Combine arrays depending on checked boxes - php

I have a form with check boxes.
I want it so that when a check box is checked, it includes an array.
<input type="checkbox" name="main" value="main" checked> Main/unsorted<br />
<input type="checkbox" name="art" value="art" checked> Art/literature/music<br />
<input type="checkbox" name="games" value="games" checked> Games/gaming<br />
If main is checked include the array 'main', if art is checked include the array 'art', etc.
I've tried, but I can't find a function that would work for this scenario.
Edit: I'm cheating a bit and am now doing it like so.
foreach($_GET as $get) {
$end = array_merge($end, $$get);
}

From your information it sounds like you want to merge an array depending on which checkboxes have been ticked? Am I correct in assuming this?
Is something like this what you are looking for?
<?php
$combinationArray = array();
$mainArray = array('item1','item2','item3');
$artArray = array('item4','item5','item6');
$gamesArray = array('item7','item8','item9');
if(isset($_POST['main']) && $_POST['main']=='main'){
$combinationArray = array_merge($combinationArray,$mainArray);
}
if(isset($_POST['art']) && $_POST['art']=='art'){
$combinationArray = array_merge($combinationArray,$artArray);
}
if(isset($_POST['games']) && $_POST['games']=='games'){
$combinationArray = array_merge($combinationArray,$gamesArray);
}
?>
HTML:
<form action="yourpage.php" method="post">
<input type="checkbox" name="main" value="main" checked> Main/unsorted<br />
<input type="checkbox" name="art" value="art" checked> Art/literature/music<br />
<input type="checkbox" name="games" value="games" checked> Games/gaming<br />
<button>
Submit
</button>
</form>

Related

how to save multiple radio button in database using php without save button value

how to save multiple radio button in database using php without save button value.
my code :
$user_id = $_POST['user_id'];
foreach ( $_POST as $key => $val ) {
if ($key <> 'user_id') {
$bidder_interst_insert="INSERT INTO bidder_interest_list(id, bidder_id, bidder_interest_name) VALUES ('','$user_id','$val')";
$bidder_interst_insert_result = mysql_query($bidder_interst_insert);
if (mysql_affected_rows() > 0) {
$interest_list_success = "Thank you Successfull insert your interst list.";
$_SESSION['interest_list_success_msg'] = $interest_list_success;
} else {
$insert_error = "interst list Insert Error.";
$_SESSION['insert_error_msg'] = $insert_error;
header("location:interest_list.php");
}
}
}
This code work but database extra save in save button value how to solved this problem??
foreach ( $_POST as $key => $val ){
You are directly looping the $_POST, so the SAVE button value is also saving in the database. Take the values individually instead of looping the whole $_POST, then the SAVE button value won't be saved in the database.
And moreover you are using mysql functions which are deprecated, use mysqli or PDO.
EDIT::
Just take it the same way as u took user_id ==> $variablename = $_POST['fieldname'];
EDIT:::
Let me suppose i have a form like this
<form name="form1" id="form1" method="post" action="">
<input type="checkbox" name="products[]" value="A" checked="checked" />A <br />
<input type="checkbox" name="products[]" value="B" checked="checked" />B <br />
<input type="checkbox" name="products[]" value="C" checked="checked" />C <br />
<input type="checkbox" name="products[]" value="D" checked="checked" />D <br />
<input type="checkbox" name="products[]" value="E" checked="checked" />E <br />
<input type="checkbox" name="products[]" value="F" checked="checked" />F <br />
<input type="submit" name="save" id="save" value="Save" />
</form>
then i can do it like:
<?php
if(isset($_POST['save']))
{
$products = $_POST['products'];
foreach($products as $key => $value)
{
$qry = mysql_query("INSERT INTO tbl(product) VALUES('$value')");
}
}
?>
Try this
unset($_POST['name-of-save-button']);
$data = $_POST;
foreach ( $data as $key => $val ){//your code here}

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 - Handling HTML checkbox array [duplicate]

I have 1 form in with multiple checkboxes in it (each with the code):
<input type="checkbox" name="check_list" value="<? echo $row['Report ID'] ?>">
Where $row['Report ID'] is a primary key in a database -so each value is different.
How would I be able to tell which checkboxes have been checked? (Maybe multiple)
This is for an inbox system and I have a button below that I want (when clicked) to delete all messages (ids of: $row['Report ID']) which have the checkbox's checked.
Set the name in the form to check_list[] and you will be able to access all the checkboxes as an array($_POST['check_list'][]).
Here's a little sample as requested:
<form action="test.php" method="post">
<input type="checkbox" name="check_list[]" value="value 1">
<input type="checkbox" name="check_list[]" value="value 2">
<input type="checkbox" name="check_list[]" value="value 3">
<input type="checkbox" name="check_list[]" value="value 4">
<input type="checkbox" name="check_list[]" value="value 5">
<input type="submit" />
</form>
<?php
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
?>
Edit To reflect what #Marc said in the comment below.
You can do a loop through all the posted values.
HTML:
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
PHP:
foreach($_POST['check_list'] as $item){
// query to delete where item = $item
}
you have to name your checkboxes accordingly:
<input type="checkbox" name="check_list[]" value="…" />
you can then access all checked checkboxes with
// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
// do something
}
ps. make sure to properly escape your output (htmlspecialchars())
<input type="checkbox" name="check_list[<? echo $row['Report ID'] ?>]" value="<? echo $row['Report ID'] ?>">
And after the post, you can loop through them:
if(!empty($_POST['check_list'])){
foreach($_POST['check_list'] as $report_id){
echo "$report_id was checked! ";
}
}
Or get a certain value posted from previous page:
if(isset($_POST['check_list'][$report_id])){
echo $report_id . " was checked!<br/>";
}
It's pretty simple. Pay attention and you'll get it right away! :)
You will create a html array, which will be then sent to php array.
Your html code will look like this:
<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">
Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.
Then, when you submit the form, your PHP array will look like this:
print_r($check_list)
[1] => checked
[3] => checked
Depending on which were checked and which were not.
I'm sure you can continue from this point forward.

Count checked checkboxes

I am new to HTML, I have a list of checkboxes on a form in an HTML page.
Each checkbox on each line represents a different category "I" "D" "C" and "S".
Part of my code is as follows:
<form>
1.<input type="checkbox" name="Personality_1.1" value="I"/>Animated &nbsp
<input type="checkbox" name="Personality_1.2" value="D" />Adventurous &nbsp
<input type="checkbox" name="Personality_1.3" value="C" />Analytical &nbsp
<input type="checkbox" name="Personality_1.4" value="S" />Adaptable<br /><br />
2.<input type="checkbox" name="Personality_2.1" value="I"/>Playful &nbsp
<input type="checkbox" name="Personality_2.2" value="D" />Persuasive &nbsp
<input type="checkbox" name="Personality_2.3" value="C" />Persistent &nbsp
<input type="checkbox" name="Personality_2.4" value="S" />Peaceful<br /><br />
3.<input type="checkbox" name="Personality_3.1" value="I"/>Sociable &nbsp
<input type="checkbox" name="Personality_3.2" value="D" />Strong Willed &nbsp
<input type="checkbox" name="Personality_3.3" value="C" />Self-sacraficing &nbsp
<input type="checkbox" name="Personality_3.4" value="S" />Submissive<br /><br />
I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then display the total of each category when the form is submitted.
Such a: "Five D's have been checked" "Three C's have been checked"
Is there a way I can do this with Javascript or PHP? If so can anyone help direct me to figure out how to do so?
Well, with PHP, assuming your submitting the form with POST:
$counts = array_count_values($_POST);
And you'll get an associative array with the values as keys and counts as values. So if for example 3 D's have been checked, $counts['D'] will hold "3".
As an example, you can use something like this:
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var allChk = document.getElementsByTagName("input"),
counts = {},
i, j, cur, val;
for (i = 0, j = allChk.length; i < j; i++) {
cur = allChk[i];
if (cur.type === "checkbox") {
if (!(cur.value in counts)) {
counts[cur.value] = 0;
}
if (cur.checked) {
counts[cur.value]++;
}
}
}
for (val in counts) {
console.log("There are " + counts[val] + " " + val + "'s checked");
}
};
};
DEMO: http://jsfiddle.net/Dwjez/1/
Click the button, after checking some checkboxes, and look at your console to see the results. It just finds all checkboxes, and stores the number of checked ones, per value, in an object literal...then the final loop is there just to print the results in the console.
This was just a simple example with event handling, but I'd suggest looking at addEventListener vs onclick to see another way to handle events (with addEventListener).
jquery-:
var numberOfCheckboxesSelected = $('input[type=checkbox]:checked').length;
javascript--:
var checkboxLength = document.forms["formName"].elements["checkbox[]"].length;
var checkboxes = document.forms["formName"].elements["checkbox[]"];
for(var i = 0; i < checkboxLength; ++i) {
if(checkboxes[i].checked) {
// do stuff
}
}
how about...
var getCount = function(type) {
return document.querySelectorAll('input[value='+type+']:checked').length;
}
alert(getCount('A') + "As have been selected");
and it looks like you would be better off using a radio group instead of checkboxes. From looking at your html, do you want the user to be able to select more than one item in each section?
Here is the code you want. Try it and let me know.
<HTML>
<HEAD>
<TITLE>Document Title</TITLE>
</HEAD>
<BODY>
<FORM NAME="f1" action="next_page.php" method="post">
<input type="checkbox" name="chkGuar[]" value="mike"> Mike<br />
<input type="checkbox" name="chkGuar[]" value="joy"> Joy<br />
<input type="checkbox" name="chkGuar[]" value="harry"> harry<br />
<input type="checkbox" name="chkGuar[]" value="watson"> watson<br />
<input type="checkbox" name="chkGuar[]" value="george"> george<br />
<input type="checkbox" name="chkGuar[]" value="peter"> Peter<br />
<input type="submit" name="chksbmt" value="Send" />
<!-- <div id="myrow" style="visibility:hidden">
<input type = text name ='txtGRTNo' tabindex = 19 size="20">
</div>
<div width="338" align="left" colspan="3" height="12"></div> !-->
</FORM>
</BODY>
</HTML>
next_page.php
<?php
if(isset($_POST['chksbmt'])){
$counts = count($_POST['chkGuar']);
echo "this is the next page. you checked $counts checkbox <br /><br />";
for($i=1;$i<=$counts;$i++){
echo "<input type='text' style='border:1px solid #000;' value='your text box here' /><br/><br/>";
}
}
You should write your form code like this:
<form>
1.<input type="checkbox" name="chkI[]" value="I1"/>Animated
<input type="checkbox" name="chkD[]" value="D1" />Adventurous
<input type="checkbox" name="chkC[]" value="C1" />Analytical
<input type="checkbox" name="chkS[]" value="S1" />Adaptable
2.<input type="checkbox" name="chkI[]" value="I2"/>Playful
<input type="checkbox" name="chkD[]" value="D2" />Persuasive
<input type="checkbox" name="chkC[]" value="C2" />Persistent
<input type="checkbox" name="chkS[]" value="S2" />Peaceful
3.<input type="checkbox" name="chkI[]" value="I3"/>Sociable
<input type="checkbox" name="chkD[]" value="D3" />Strong Willed
<input type="checkbox" name="chkC[]" value="C3" />Self-sacraficing
<input type="checkbox" name="chkS[]" value="S3" />Submissive
</form>
Look at the "name" and "value" attributes. I made I change to the values of them.
You say:
I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then
display the total of each category when the form is submitted.
If you make a submit...
<?php
if(!empty($_GET['chkD'])) {
$counterChkD = 0;
foreach ($_GET['chkD'] as $chkD){
echo $chkD."\n";
//echoes the value set in the HTML form for each checked checkbox associated with the "D" value
//so, if I were to check "Adventurous", "Persuasive", and "Strong Willed" it would echo value D1, value D2, value D3.
$counterChkD++;
}
echo "# of 'D-CheckBoxes' checked: ".$counterChkD."\n";
}
?>

How to enable or disable check boxes based on a click event?

I have a web app (PHP) and I have to make this change. I am more of a database, scripting guy, please bear with me on this one!
I have 8 check boxes (think numbered 1~8) in a form. I have to implement a condition where in :
If one of the first 4 checkboxes are checked (only one checkbox can be checked in the first 4),
Then the next 4 checkboxes should be disabled
Else the next 4 checkboxes should be enabled.
My solution :
Make the first 4 checkboxes radiobuttons to confirm to the only one
checkbox can be selected condition.
Disable/Enable the next 4 checkboxes based on the above action. So,
if the radiobutton is not selected, then the next 4 checkboxes should
be available for selection.
I have to actually disable the checkboxes rather than hide using jQuery, so the checkboxes should be solidgray (uncheckable) when disabled.
Sample code (stripped off some formatting mess for others looking for a similar solution) :
<div>
<input type="checkbox" name="check1" value="1" id="check1" <?php if (!empty($rows['check1'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check2" value="1" id="check2" <?php if (!empty($rows['check2'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check3" value="1" id="check3" <?php if (!empty($rows['check3'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check4" value="1" id="check4" <?php if (!empty($rows['check4'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check5" value="1" id="check5" <?php if (!empty($rows['check5'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check6" value="1" id="check6" <?php if (!empty($rows['check6'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check7" value="1" id="check7" <?php if (!empty($rows['check7'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check8" value="1" id="check8" <?php if (!empty($rows['check8'])) { echo 'checked="checked"'; } ?> />
</div>
My requests :
What is the most efficient way of doing this? (simple without complicating the problem)
Any sample code is greatly appreciated.
I think this is what you're looking for. You can achieve it using .index() to get current clicked checkbox. .slice() is used to get all elements at index 4 and after.
$('input[type=checkbox]').change(function(){
var $linputs = $('input[type=checkbox]').slice(4);
var $this = $(this);
$linputs.prop('disabled',($this.index() < 4 && this.checked));
if($this.index() < 4 && this.checked){
$linputs.prop('checked',false);
}
});​
FIDDDLE
Or is it something like this that you want? Where only one of the first four checkboxes can be checked. If one is checked then all the others will be disabled.
$('input[type=checkbox]').change(function(){
var $this = $(this);
$(linputs).prop('disabled',($this.index() < 4 && this.checked));
if($this.index() < 4 && this.checked){
$(linputs).prop('checked',false);
}
});​
http://jsfiddle.net/h5wDr/
EDIT:
if you have other checkboxes in the page and want to be able to separate them from this logic, you can add context in the selector so it keeps this code isolated to only those within this div like so
<div id='test'>
<input type="checkbox" name="check1" value="1" id="check1" >first
<input type="checkbox" name="check2" value="1" id="check2" >second
<input type="checkbox" name="check3" value="1" id="check3" >third
<input type="checkbox" name="check4" value="1" id="check4" >fourth
<input type="checkbox" name="check5" value="1" id="check5" >fifth
<input type="checkbox" name="check6" value="1" id="check6" >sixth
<input type="checkbox" name="check7" value="1" id="check7" >seventh
<input type="checkbox" name="check8" value="1" id="check8" >eight
</div>
Then just add the context
var $inputs = $('input[type=checkbox]', $('#test'));
// this will only select checkboxes within the element with id=test
http://jsfiddle.net/h5wDr/2/
<div>
<input type="checkbox" name="check1" value="1" id="check1" />
<input type="checkbox" name="check2" value="1" id="check2" />
<input type="checkbox" name="check3" value="1" id="check3" />
<input type="checkbox" name="check4" value="1" id="check4" />
<input type="checkbox" name="check5" value="1" id="check5" />
<input type="checkbox" name="check6" value="1" id="check6" />
<input type="checkbox" name="check7" value="1" id="check7" />
<input type="checkbox" name="check8" value="1" id="check8" />
</div>
<script>
$(document).ready(function () {
var $firstFourChecks = $("#check1,#check2,#check3,#check4");
var $lastFourChecks = $("#check5,#check6,#check7,#check8");
$firstFourChecks.on('click', function (e) {
var isCheck = $(this).is(':checked');
$firstFourChecks.not($(this)).prop('checked', false);
$(this).prop('checked', isCheck);
if (isCheck) {
$lastFourChecks.prop("disabled", true).prop('checked', false);
} else {
$lastFourChecks.prop("disabled", false);
}
});
});
</script>
This is entirely done in javascript, and is agnostic to the fact you are using php. Essentially, we make sure in the first four for you have not selected, they are set to false. Then we toggle the state of the one clicked.
If you clicked something on in your first four the last four are turned off and disabled, otherwise they are renabled. This matches the posted pseudocode.
You should be able to paste this directly in. The selectors are cached for speed reasons.
http://jsfiddle.net/L4qeN/ see it here.
Edit: wow looks like someone beat me to the punchline by only a few minutes. We did use very different methods; however.
You would have to try it yourself, but I would do something like (using javascript):
Add a class to every checkbox of the first group and another class to every checkbox of the second group;
Check for change events for the first class, turn off all of the first group but the clicked one;
Check if any of the first group is selected and activate / deactivate the second class group accordingly.
Give your first four checkboxes one class and then your second four a second class and then add onclick handlers to all the first checkboxes:
$('.firstfour_class').click(
if $('input:checkbox:checked.firstfour_class').length > 1){
//code to turn OFF the second four and make them unchecked
} else {
//code to turn ON the second four
}
})
Check out the jQuery :checked selector.

Categories