Count checked checkbox(array) numbers & saving checked checkboxes - javascript

I have an array of checkbox in a table in PHP file like this :
echo "<td $Blocked><input type =\"checkbox\" name=\"Blocked[]\" value=\"checkblock\" /></td>";
I am trying to get the value of number of checked checkboxes and save it to DB.
$Blocked = 'unchecked';
if ((isset($_POST['edit_tc']))) {
if (isset($_POST['Blocked'])) {
if (is_array($_POST['Blocked'])) {
foreach($_POST['Blocked'] as $value) {
error_log($value);
}
}
else {
$value = $_POST['Blocked'];
error_log($value);
}
$Blocked = 'checked';
}
}
"edit_tc" is the Submit button.
How do I take the number of it when the user checks the checkbox & clicks Submit button to save it to a table column?

I guess below code will solve all your problem.
<?php
$hello = array();
if(isset($_POST['submit'])) {
extract($_POST);
print_r($hello); //print all checked elements
}
?>
<form method="post">
<input type="checkbox" name="hello[]" value="1" <?php if(in_array(1, $hello)){ echo 'checked'; } ?>>
<input type="checkbox" name="hello[]" value="2" <?php if(in_array(2, $hello)){ echo 'checked'; } ?>>
<input type="checkbox" name="hello[]" value="3" <?php if(in_array(3, $hello)){ echo 'checked'; } ?>>
<input type="checkbox" name="hello[]" value="4" <?php if(in_array(4, $hello)){ echo 'checked'; } ?>>
<button type="submit" name="submit" value="Submit">Submit</button>
</form>
You have to check the value of each checkbox inside the checkbox array you are getting using in_arrayfunction of PHP.
If you need to understand whole thing, just let me know.
Will be glad to help you out.
Regards.

You can use this method...
if ((isset($_POST['edit_tc']))) {
if (isset($_POST['Blocked']))
{
$data = $_POST['Blocked'];
foreach ($data as $checkedValue)
{
$qry = mysql_query("INSERT INTO `Table_name` WHERE `column_id` = '$checkedValue'");
}
}
}
This is the method that will use to save each value as different records... You can modify that if needed.

You can simply use count() function to get total number of checkbox checked by user.
As only those checkbox values are posted to submitted page which are checked by user and if checkbox is not checked , its value will not be submitted. i.e The unchecked checkbox will not exist on submitted page.
USE:
$totalCheckboxChecked=count($_POST['Blocked']);

Related

Keep the selected radio button checked and clicked upon page refresh?

i have a radio input whose values are coming dynamically and creating multiple radio fields. Long list of radio fields are displayed.
<?php
for ($i = 0; $i < $total_trades; $i++) {
$array_trade_data = $data_trade_data[$i];
$Trade_name = $array_trade_data['name'];
$Trade_id = $array_trade_data['id'];
?>
<input type="radio" class="trade" id="<?php echo $Trade_id; ?>" name="trade" value="<?php echo $Trade_id; ?>" ><?php echo $Trade_name; ?><br>
<?php } ?>
I want to Keep the selected radio button checked and clicked upon page refresh.
you cold use checked attribute
<input type="radio" name="trade">1<br>
<input type="radio" name="trade" checked>2<br>
<input type="radio" name="trade">3
to click something like
<script>document.getelementbyid("<?php echo $Trade_id; ?>").click();</script>

PHP form text field to mysql based on selected checkbox [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create sign up form, where it has multiple text field (name, email, phone, ..) and have multiple checkbox options.
I also created multiple tables in mysql database, one for each checkbox.
My goal is to store values in text field to selected checkbox data table.
My question is how can I create if statement to look what checkbox is selected, so it will store input of text field to that table
input.php
<html>
<head>
</head>
<script type="text/javascript">
function toggle(source) {
checkboxes = document.getElementsByName('chk1[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<body>
<h2><font color="white">Welcome to Cars and Coffee</h2>
<p>Sign up to receive if you are interested in
receiving information from Cars and Coffee.</p>
<p>Please select at least one option</p>
<form name="newEntry" action="page.php" method="POST">
name<input type=text length=60 size=30 name="name"><br>
email<input type=text length=60 size=30 name="email"><br>
car<input type=text length=60 size=30 name="car"><br>
phone<input type=text length=60 size=30 name="phone"><br>
<input type="submit" name="submit" email="add" car="add" phone="add" >
</form>
<form action="page.php" method="POST">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
</form>
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
$qh = mysql_query("select * from all_emails order by id desc");
if (#mysql_num_rows($qh)) { /* the if(#...) syntax makes PHP supress any
warnings that might come out of that function. */
/* mysql_fetch_object(query handle);
* returns an object whose contents are that of one rotw in the
database. */
while ($obj = mysql_fetch_object($qh)) {
echo "
<p>
$obj->email<br>
$obj->name<br>
$obj->car<br>
$obj->phone<br>
<p>
<hr>
";
}
}
?>
</body>
</html>
page.php
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
mysql_query("insert into all_emails (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
?>
<html>
<head>
<meta http-equiv=refresh content="0; URL=./input.php">
</head>
</html>
Here is the if statement I am trying.
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
if( isset($_POST["cars_coffee"] ) ) {
$sql = "INSERT INTO cars_and_coffee (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']‌​."', '".$_POST['phone']."' )");
mysql_query($sql) or die(mysql_error());
}
echo "Record is inserted";
}
?>
Hi use the following code :
NOTE : I highly suggest you to use mysqli or PDO. mysql functions are deprecated and are obsolate.
Please sanitize or safe cast your data before inserting into your database.
Also NOTE: In form I am redirecting to the same form page. Please use the appropriate php file name or routing path.
db_connect.php
$host = 'localhost';
$user = 'root';
$password = 'root';
$database = 'skerp';
$connection_error = 'Sorry!!! We are experiencing problems with the database settings';
$link = mysqli_connect($host, $user, $password, $database) or DIE($connection_error);
The following is the implementation
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if($_SERVER['REQUEST_METHOD'] == 'POST'){
include_once ('db_connection.php');
if(in_array('cars_coffee', $_POST['chk'])){
$emails = mysqli_query($link, "INSERT INTO all_emails (name, email, car, phone) VALUES ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
}else{
//If it fails then put the condition here or you may skip else part
echo 'Not Exists';
}
echo '<pre>';
print_r($_POST);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Hope it helps. Happy Coding!
You can use the isset method to check if a checkbox was selected.
if ( isset ( $_POST ["cars_coffee"] ) )
{
// do something
}
if ( isset ( $_POST ["kentucky"] ) )
{
// do something else
}
...
There seems to be a slight problem with your logic because you are using checkboxes to retrieve data from the user. If you want the user to only select one checkbox, use a radio button. That will make them unable to select multiple. If I'm just not understanding you correctly and you really do want users to be able to select multiple boxes, then keep using checkboxes, but change the name attribute of each checkbox to be unique. Because right now, every checkbox has the same name, so it is going to read only the last checkbox that they checked.
The logic would go something like this if you continued using checkboxes and gave each checkbox a unique name:
$sql = '';
// make sure that the checkbox is set
if(isset($_POST['kentucky_checkbox'])){
{
$sql += 'INSERT INTO kentucky VALUES ...;';
}
if(isset($_POST['labor_checkbox'])){
{
$sql += 'INSERT INTO labor VALUES ...;';
}
etc.
...
// execute $sql
The logic would go something like this if you used radio buttons:
// make sure that the variable is set
if(isset($_POST['chk[]'])){
{
// check what the value is
switch ($_POST['chk[]']) {
case 'option1':
// set the table
$table = 'table1';
break;
case 'option2':
$table = 'table2';
break;
case 'option3':
$table = 'table3';
break;
}
}
...
$sql = 'INSERT INTO ' . $table . ' VALUES ...';

select option dropdown onchange update variable

Here is my dilemma. A multi-select drop-down displays pre-selected options. When the user makes any changes, I'm running some code in the PHP action file (called through a submit button). I'm trying to accomplish this using a flag and updating the flag in the onchange event of "select option". The rest is working fine. I just wanted to execute the queries in action file only when the user changed selections in drop down rather than every time the form is submitted. However I'm unable to pass the flag successfully. I know I'm missing something basic and have spent two days looking at it. Any help is appreciated.
The relevant code is pasted below:
//Initialize flag
<?php
...
$multi_prog_change_flag = '0';
...
?>
//Hidden Form Element
<form action="update_u.php" method="post" id="cForm" name="cForm" onsubmit="return validateForm()" autocomplete="off">
...
<?php echo '<input type="hidden" id="email" value="'.$email.'"> ';?>
<?php echo '<input type="hidden" id="multiprogchangeflag" name="multiprogchangeflag" value="'.$multi_prog_change_flag.'"> ';?>
...
// Drop-down Element where update is triggered
<tr id="odd">
<td><select id="programName" name="programName[]" onchange="updateflag();>" multiple="multiple" size=10>
..
<option name="drop1" value ="<?php echo $data['Program_Id'] ?>" <?php if ($data[curr_prog] == '1') echo 'selected="selected"'; ?>> <?php echo $data['Program_Name'];?></option>
..
</select>
<input type="hidden" id="pNames" name="pNames" value="" />
</td>
</tr>
// Function to update flag
function updateflag() {
<document.getElementById("multiprogchangeflag").value = "1";
}
// update_u.php PHP Action File
$multi_prog_flag=mysql_real_escape_string($_POST['multiprogchangeflag']);
if ($multi_prog_flag == '1'){
$multi_prog_delete_query=mysql_query("UPDATE multi_prog_access SET is_act = '0', Updated_by = '$updatedby', update_timestamp = NOW() WHERE user_id = '$useid'");
$count = count($multi_prog_names);
for($i=0;$i<$count;$i++){
$multi_prog_ID=$multi_prog_names[$i];
$multi_prog_update_query=mysql_query("INSERT INTO multi_prog_access (user_id, Prog_id, created_by, is_act, Update_timestamp) VALUES ('$ids','$multi_prog_ID', '$updatedby', '1', NOW())");
}
}

How to keep php $_GET value from a submit button after form submit from javascript?

I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name

How to check if a radio button is clicked?

My code looks like this:
form action="familytree.php" method="post">
<?php
foreach ($spouses as $spouse) {
if (!empty($spouse['mname'])) {
$name = $spouse['fname'].' '.$spouse['lname'].' ('.$spouse['mname'].')';
}
else {
$name = $spouse['fname'].' '.$spouse['lname'];
}
if ($spouse['ended'] == '1') {
$married = '';
$divorced = 'checked';
}
else {
$married = 'checked';
$divorced = '';
}
?>
<div class="form_section dates">
<h3><?php echo $name; ?></h3>
<p>
<input type="radio" id="married_option" name="married_divorced_options" <?php echo $married; ?> value="1"/>
<label for="edate">Married</label>
<input type="radio" id="divorced_option" name="married_divorced_options" <?php echo $divorced; ?> value="1"/>
<label for="sdate">Divorced</label>
</p>
<div class="half" style="display: inline">
<input type="text" name="sdate_<?php echo $spouse['individual_id']?>" id="sdate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['start_date']; ?>" placeholder="Rašykite sutuoktuvių datą čia"/>
<?php echo $this->formError->error("sdate_".$spouse['individual_id'].""); ?>
</div>
<div id="divorced" class="half" style="display:none">
<input type="text" name="edate_<?php echo $spouse['individual_id']?>" id="edate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['end_date']; ?>" placeholder="Rašykite skyrybų datą čia"/>
<?php echo $this->formError->error("edate_".$spouse['individual_id'].""); ?>
</div>
</div>
<?php
}
?>
<p class="submit">
<input class="first-btn" type="submit" id="edit-relationship" name="edit-relationship" value="Edit"/>
</p>
</form>
jQuery("#divorced_option").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("#married_option").click(function() {
document.getElementById("divorced").style.display = "none";
});
What I would like to know is how to check if a radio button is clicked when you don't know its full name, only half of it. For example, #divorced_option is not full name, it should be something like this #divorced_option_161, #divorced_option_161... So, the code should check if the radio button that has divorced_option in its name is clicked. Is there a way to achieve this?
EDIT
It works with jQuery("[id^='married_option']").click(function(){}). But I forgot to mention in my original question that the element divorced isn't full name as well, it should be divorced_161, divorced_162, depending of the name of the radio button that is clicked. How can I hide the element that matches with the radio button?
Use the attribute starts with selector (ex. [name^="value"]):
jQuery("[id^='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id^='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
Have a look at the jQuery selectors.
The 'Attribute Contains' selector would be useful here, which means your code would be :
jQuery("[id*='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id*='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
You can select the elements based on the #divorced_option_[number] pattern while checking if they are selected like this:
$("input[id*=divorced_option]:checked");
If you would like to check wether the divorced_option substring is in the name="" attribute of the radio element, then change the id from the selector to name, like so:
$("input[name*=divorced_option]:checked");
After this, just check wether or not jQuery returned an actual element.

Categories