I have added a checkbox to a form that the user can dynamically add rows to. You can see the form here.
I use an array to pass the values for each row to a PHP email generator, and all works fine for other inputs, but I can't get the checkbox to work. The checkbox input currently looks like this:
<input type="checkbox" name="mailing[]" value="Yes">
Then in the PHP I have this:
$mailing = trim(stripslashes($_POST['mailing'][$i]));
But it is not working as expected, i.e. I am only seeing 'Yes' for the first checkbox checked, and nothing for subsequent checkboxes that are checked.
One further issue is that I would like the value 'No' to be generated for unchecked checkboxes.
Could someone help with this?
Thanks,
Nick
Form:
<form method="post" action="bookingenginetest.php">
<p>
<input type="checkbox" name="mailing[]" value="Yes">
<label>Full Name:</label> <input type="text" name="name[]">
<label>Email:</label> <input type="text" name="email[]">
<label>Telephone:</label> <input type="text" name="telephone[]">
<span class="remove">Remove</span>
</p>
<p>
<span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" />
</p>
</form>
Cloning script:
$(document).ready(function() {
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
x.find('input').each(function() { this.value = ''; });
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
});
$mailing = array();
foreach($_POST as $v){
$mailing[] = trim(stripslashes($v));
}
To handle unchecked boxes it would be better to set each checkbox with a unique value:
<input type="checkbox" name="mailing[1]" value="Yes">
<input type="checkbox" name="mailing[2]" value="Yes">
or
<input type="checkbox" name="mailing[a]" value="Yes">
<input type="checkbox" name="mailing[b]" value="Yes">
Then have a list of the checkboxes:
$boxes = array(1,2,3);
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
foreach($boxes as $v){
if(array_key_exists($v,$p)){
$mailing[$v] = trim(stripslashes($p[$v]));
}else{
$mailing[$v] = 'No';
}
}
print_r($mailing);
You could also use this with a number of checkboxes instead:
$boxes = 3;
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
for($v = 0; $v < $boxes; $v++){
if(array_key_exists($v,$p)){
$mailing[$v] = trim(stripslashes($p[$v]));
}else{
$mailing[$v] = 'No';
}
}
print_r($mailing);
Here's my solution:
With an array of checkboxes in the html like so...
<input type="hidden" name="something[]" value="off" />
<input type="checkbox" name="something[]" />
<input type="hidden" name="something[]" value="off" />
<input type="checkbox" name="something[]" />
<input type="hidden" name="something[]" value="off" />
<input type="checkbox" name="something[]" />
I then fix the posted array with this function...
$_POST[ 'something' ] = $this->fixArrayOfCheckboxes( $_POST[ 'something' ] );
function fixArrayOfCheckboxes( $checks ) {
$newChecks = array();
for( $i = 0; $i < count( $checks ); $i++ ) {
if( $checks[ $i ] == 'off' && $checks[ $i + 1 ] == 'on' ) {
$newChecks[] = 'on';
$i++;
}
else {
$newChecks[] = 'off';
}
}
return $newChecks;
}
This will give me an array with values of either 'on' or 'off' for each (and every) checkbox.
Note that the hidden input MUST be BEFORE the checkbox input in order for the function to work right.
Change the value for each checkbox to something unique:
<input type="checkbox" name="mailing[]" value="Yes-1">
<input type="checkbox" name="mailing[]" value="Yes-2">
etc. In order to do this from your jQuery code, add another line that assigns the value to the new checkbox:
x.find('input:checkbox').each(function() { this.value='Yes-'+n; });
You'll have to define n on the initial page load. Assuming you start with only one "person", just add right above your $(".add").click handler:
var n=1;
And then:
in your $(".add").click handler, increment the value of n
in your $(".remove").click handler, decrement the value of n
To get checked and unchecked both values in POST place a hidden field with exactly the same name but with opposite value as compared to the original chkbox value such that in this case the value will be '0'
<input type="hidden" name="chk_name[]" value="0" />
<input type="checkbox" name="chk_name[]" value="1"/>
<input type="hidden" name="chk_name[]" value="0" />
<input type="checkbox" name="chk_name[]" value="1"/>
<?php
function getAllChkboxValues($chk_name) {
$found = array(); //create a new array
foreach($chk_name as $key => $val) {
//echo "KEY::".$key."VALue::".$val."<br>";
if($val == '1') { //replace '1' with the value you want to search
$found[] = $key;
}
}
foreach($found as $kev_f => $val_f) {
unset($chk_name[$val_f-1]); //unset the index of un-necessary values in array
}
final_arr = array(); //create the final array
return $final_arr = array_values($chk_name); //sort the resulting array again
}
$chkox_arr = getAllChkboxValues($_POST['chk_name']); //Chkbox Values
echo"<pre>";
print_r($chkox_arr);
?>
Here's my solution:
<span>
<input class="chkBox" onchange="if($(this).is(':checked')){$(this).parent().find('.hidVal').prop('disabled',true);}else{$(this).parent().find('.hidVal').prop('disabled', false);}" type="checkbox" checked name="session[]" value="checked_value_here" />
<input type="hidden" class="hidVal" name="session[]" value="un_checked_value_here" />
</span>
<span>
<input class="chkBox" onchange="if($(this).is(':checked')){$(this).parent().find('.hidVal').prop('disabled',true);}else{$(this).parent().find('.hidVal').prop('disabled', false);}" type="checkbox" checked name="session[]" value="checked_value_here" />
<input type="hidden" class="hidVal" name="session[]" value="un_checked_value_here" />
</span>
Related
Im having problem on how to get the value of the hidden input box once the checkbox is checked. here are my code.
<label class="control control--checkbox"><span>Additional</span>
<input type="checkbox" name="apply[]" value=""/>
<input type="hidden" name="option[]" value="1 bottle"/>
<input type="hidden" name="cost[]" value="$20"/>
</label>
<label class="control control--checkbox"><span>Additional</span>
<input type="checkbox" name="apply[]" value=""/>
<input type="hidden" name="option[]" value="3 bottle"/>
<input type="hidden" name="cost[]" value="$50"/>
</label>
My Php code:
<?php
$options = $_POST['option'];
$costs = $_POST['cost'];
$apply = $_POST['apply'];
if (isset($apply)) {
foreach ($options as $option) {
echo '<tr>';
echo '<td>'.$option.'</td>';
echo '</tr>';
}
}
?>
It seems that the option of my php code is always two, i want only to display that was checked and dont display that are not.
can someone advise me on how can i solve this problem or any work around to get the same result?
Using PHP you need to set the CheckBox value and then are able to find the other values.
<input type="checkbox" name="apply[]" value="y"/>
PHP
$options = $_POST['option'];
$costs = $_POST['cost'];
$apply = $_POST['apply'];
if(isset($apply)) {
foreach ($options as $key => $option) {
if($option == 'y'){
echo $costs[$key];
echo $apply[$key];
}
}
}
Using jQuery you can get the Hidden values like-
$(function(){
$('.input_check').on("change", function(){
var chk = $(this).prop('checked');
if(chk == true){
var val = $(this).closest('label').find('.option').val();
console.log(val);
}
})
})
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}
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  
<input type="checkbox" name="Personality_1.2" value="D" />Adventurous  
<input type="checkbox" name="Personality_1.3" value="C" />Analytical  
<input type="checkbox" name="Personality_1.4" value="S" />Adaptable<br /><br />
2.<input type="checkbox" name="Personality_2.1" value="I"/>Playful  
<input type="checkbox" name="Personality_2.2" value="D" />Persuasive  
<input type="checkbox" name="Personality_2.3" value="C" />Persistent  
<input type="checkbox" name="Personality_2.4" value="S" />Peaceful<br /><br />
3.<input type="checkbox" name="Personality_3.1" value="I"/>Sociable  
<input type="checkbox" name="Personality_3.2" value="D" />Strong Willed  
<input type="checkbox" name="Personality_3.3" value="C" />Self-sacraficing  
<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";
}
?>
Assuming I have the following form:
<form action="process.php">
<input type="checkbox" name="option1" value="oats"> Oats
<input type="checkbox" name="option2" value="beans"> Beans
<input type="hidden" name="parameter" value="a"/>
<input type="submit" value="Submit"/>
</form>
What would normally happen is after clicking on the URL, the browser redirects to:
process.php?option1=oats&option2=beans¶meter=a
How do I make it such that when the submit is clicked all the checkboxes end up as part of the "parameter", but separated by commas? So in other words it would be:
process.php?parameter=a,oats,beans
Best solution with minimal javascript/jquery/html is best if no html solution.
If you want several values in one parameter, you have to name it like parameter[]
f.e.:
<form action="process.php">
<input type="checkbox" name="parameter[]" value="oats"> Oats
<input type="checkbox" name="parameter[]" value="beans"> Beans
<input type="hidden" name="parameter[]" value="a"/>
<input type="submit" value="Submit"/>
</form>
More or less here the idea:
first form, 1 hidden input will catch all the vaules of second and void form
<script type="text/javascript">
function myfunc(){
$('#void input').each(function(id,elem){
b = $("#res").val();
if(b.length > 0){
$("#res").val( b + ',' + $(this).val() );
} else {
$("#res").val( $(this).val() );
}
});
alert("VAL "+$("#res").val());
$("#real").submit();
return false;
}
</script>
<form id="real" action="process.php">
<input id="res" type="hidden" name="parameter" value=""/>
</form>
<form id="void">
<input type="checkbox" name="option1" value="oats"> Oats
<input type="checkbox" name="option2" value="beans"> Beans
<input type="hidden" name="parameter" value="a"/>
<input type="submit" value="Submit" onClick="javascript:myfunc()"/>
</form>
add some fix, submit the right form. Tested on jsfiddle:
JsFiddel "working" example
ADD SINGLE FORM VERSION
You've to know the name of the field, and ignore the other params in the answer
<script type="text/javascript">
function myfunc(){
// can use more selector
$('#real input').each(function(id,elem){
// append the data to this field so no need to process it
if(this.id == 'res'){
return;
}
// here I concat the values
b = $("#res").val();
if(b.length > 0){
$("#res").val( b + ',' + $(this).val() );
} else {
$("#res").val( $(this).val() );
}
});
alert("VAL "+$("#res").val()); // remove me
$("#real").submit();
return false;
}
</script>
<form id='real' method='POST' action="#">
<input type="checkbox" name="option1" value="oats"> Oats
<input type="checkbox" name="option2" value="beans"> Beans
<input id="res" type="hidden" name="parameter" value="a"/>
<input type="submit" value="Submit" onClick="javascript:myfunc()"/>
</form>
There is a very useful method to use for dynamic data grouping.
<form action="file.php" method="post">
<?php for ( $i = 0; $i < count( $something ); $++ ) { ?>
<input type="checkbox" name="<?php $something[$i]; ?>[]" value="user_id"> Oats
<input type="checkbox" name="<?php $something[$i]; ?>[]" value="user_name"> Beans
<?php } ?>
<input type="submit" value="Submit"/>
</form>
I was really only interested in checkboxes that were actually checked - so I built myfunc() from the other examples like this:
function myfunc(){
$('#void input[type="checkbox"]').each(function(id,elem){
if ( ! $(this).is(':checked') ) return;
b = $("#res").val();
if(b.length > 0){
$("#res").val( b + ',' + $(this).val() );
} else {
$("#res").val( $(this).val() );
}
});
var stuff = $("#res").val();
if ( stuff.length < 1 ) {
alert('Please select at least one');
} else {
$("#real").submit();
}
}
I am creating an online order form for multiple products. I need to calculate the total cost for the products selected via checkbox and send it as a confirmation e-mail. The value of the checkbox is the price in dollars.
<input type="checkbox" id="product1" name="product1" value="100" />
<input type="checkbox" id="product2" name="product2" value="250" />
In my 'process.php' file, I need to total the cost for all items if they are checked.
if(isset($_POST['product1']) && $_POST['product1'] == '100') {
$product1 = 100;
}
if(isset($_POST['product2']) && $_POST['product2'] == '250') {
$product2 = 250;
}
$dollars = $product1 + $product2;
When I try to do it this way, $dollars is an empty variable "". Can someone tell me how to fix this?
Thank you!
There is no syntactical error in your code. So the only explanation is that,
$_POST['product1'] does not have value 100 or they are not sent through post at all
$_POST['product2'] also does not have value 250 or they are not sent through post as well
In order to verify this, do a quick var_dump($_POST) at the top of your .php file
This works, so something does not work in your code but we cant see it right now
<?php
if(isset($_POST['submit']) ) {
if(isset($_POST['product1']) && $_POST['product1'] == '100') {
$product1 = 100;
}
if(isset($_POST['product2']) && $_POST['product2'] == '250') {
$product2 = 250;
}
echo $dollars = $product1 + $product2;
}
?>
<form method="post">
<input type="checkbox" id="product1" name="product1" value="100" />
<input type="checkbox" id="product2" name="product2" value="250" />
<input type="submit" name="submit" />
</form>
You can post an array of checkbox if you want. Try this :
<?php
$dollars = 0;
// If the user post the form
if(isset($_POST['value'])) {
foreach ($_POST['product'] as $product) {
if(is_numeric($product) && $product >= 0) {
$dollars += $product;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<p>Product : <?php echo $dollars; ?></p>
<form method="post">
<label><input type="checkbox" name="product[]" value="100" /> 100</label><br/>
<label><input type="checkbox" name="product[]" value="250" /> 250</label><br/>
<label><input type="checkbox" name="product[]" value="350" /> 350</label><br/>
<label><input type="checkbox" name="product[]" value="20" /> 20</label><br/>
<label><input type="checkbox" name="product[]" value="25" /> 25</label><br/>
<input type="submit" name="value" />
</form>
</body>
</html>
This code gets an array of selected products and make the sum.
Checkbox values are not sent to the server with POST data if not checked. (edited post)
If you must POST this data, consider using a <input type="hidden" name="product1value" value="100"/> to send the value instead? Keep the check boxes just to see if they are ticked.