Total result for PHP - php

I have a form built with checkboxes but I am unable to calculate the total result for it. I want to get the total if user selects three checkboxes total will be $3 if one then $1. I am stuck as I am unable to do the calculation.
<html
<head>
<title>Order</title>
</head>
<body>
<link rel= "stylesheet" href= "order.css">
<form action="complete.php" method="post">
<form name="order">
<fieldset><legend>Complete Order:</legend>
<h1> Choose Design </h1>
<p><label>Your Name: <input type="text" name="name"></label>
<label>Address: <input type="text" name="address"></label>
<label>Credit Card #: <input type="text" name="creditcard"></label>
<label>Date: <input type="date" id="datepicker" name='date' size='9' value="" > </label>
<br><label> Design Types: <img src="1.jpg"><input type="checkbox" name="1"></label> $1.00
<label><img src="2.jpg"><input type="checkbox" name="2"> </label>$1.00
<label><img src="3.jpg"><input type="checkbox" name="3"> </label>$1.00
<br></p>
<input type="submit" value="Submit Order">
</form>
</body>
</html>
Php code
<html>
<head>
<title>Form Feedback</title>
</head>
<body>
<?php
if ( !empty($_POST['name']) && !empty($_POST['address']) && !empty($_POST['creditcard']) ) {
echo "<p>Thank you, <strong>{$_POST['name']}</strong>, for placing the order.
<p>Your item will be shipped to:
<tt>{$_POST['address']}</tt></p>
<p>Following credit card has been charged: <em>{$_POST['creditcard']}</em>.</p>\n";
} else { //Missing form value.
echo '<p>Please go back and fill out the form again.</p>';
}
?>
</body>
</html>

Changes in HTML:
<label><img src="1.jpg"><input type="checkbox" name="fieldname[]" value="1"></label> $1.00
<label><img src="2.jpg"><input type="checkbox" name="fieldname[]" value="1"> </label>$1.00
<label><img src="3.jpg"><input type="checkbox" name="fieldname[]" value="1"> </label>$1.00
PHP Code: it will count number of selected checkboxes-
<?php
if(isset($_POST['fieldname']) && !empty($_POST['fieldname'])){
echo count($_POST['fieldname']); //count the number of selected checkbox
echo array_sum($_POST['fieldname']); //sum of selected checkbox values
}
?>

Use isset($_POST['checkboxName']) to check if the checkbox is checked and then add 1 for each checkbox:
$check_value = 0;
$check_value += isset($_POST['1']) ? 1 : 0;
$check_value += isset($_POST['2']) ? 1 : 0;
$check_value += isset($_POST['3']) ? 1 : 0;

Change the php part:
<?php
if ( !empty($_POST['name']) && !empty($_POST['address']) && !empty($_POST['creditcard']) ) {
$cost = 0;
if(isset($_POST['1'])) $cost += 1;
if(isset($_POST['2'])) $cost += 1;
if(isset($_POST['3'])) $cost += 1;
echo "<p>Thank you, <strong>{$_POST['name']}</strong>, for placing the order.
<p>Your item will be shipped to:
<tt>{$_POST['address']}</tt></p>
<p>Following credit card has been charged: <em>{$_POST['creditcard']}</em>.</p>
<p>With amount: <em>{$cost}</em>.</p>\n";
} else { //Missing form value.
echo '<p>Please go back and fill out the form again.</p>';
}
?>

First of all, it's about checkbox's name. If they are a group of values (e.g: products), use a common name as an array:
<input type="checkbox" name="product[]" />
<input type="checkbox" name="product[]" />
<input type="checkbox" name="product[]" />
The second question, shouldn't your checkbox has a value or it'll be always $
1.00?
It it'll be always $1.00, just count it:
$value = isset($_POST['product']) ? count($_POST['product']) : 0;
If it should has a value:
<input type="checkbox" name="product[]" value="1.00" />
<input type="checkbox" name="product[]" value="1.50" />
<input type="checkbox" name="product[]" value="2.00" />
Can use the array_sum function:
$value = isset($_POST['product']) ? array_sum($_POST['product']) : 0;

Related

Calculating total in PHP

I have my form done but I am trying to create a handling form which calculates the total plus shipping of $5 and 8% tax rate and displays it.
Need a handling form for my following PHP code. The handling form should calculate total price, 8%tax, $5 shipping fee. It should say thank you for ordering (name entered in form) on (date entered in form)
Need a handling form for my following PHP code. The handling form should calculate total price, 8%tax, $5 shipping fee. It should say thank you for ordering (name entered in form) on (date entered in form)
<html
<head>
</head>
<body>
<link rel= "stylesheet" href= "order.css">
<form action="complete.php" method="post">
<form name="order">
<fieldset><legend>Complete Order:</legend>
<h1> Choose Design </h1>
<p><label>Your Name: <input type="text" name="name"></label>
<label>Address: <input type="text" name="address"></label>
<label>Credit Card #: <input type="text" name="creditcard"></label>
<label>Date: <input type="date" id="datepicker" name='date' size='9' value="" > </label>
<br><label> Design Types: <img src="1.jpg"><input type="checkbox" name="1"></label> $1.00
<label><img src="2.jpg"><input type="checkbox" name="2"> </label>$1.00
<label><img src="3.jpg"><input type="checkbox" name="3"> </label>$1.00
<br></p>
<input type="submit" value="Submit Order">
</form>
</body>
</html>
This is the handler, but before I start on the answer. I just wish to make it clear that Stack Overflow is a Q&A environment and not a place for someone to do your work. That being said, I have answered this question...
Place this code at the top of the HTML page that I will post (I have made some amendments).
Note the $date variable uses the ternary operator to ensure a date will get posted to the database. I have formatted the date in the yyyy-mm-dd format which is the format of MySQL databases (I'm not sure about the format the others use, but I imagine it is the same).
<?php
// only run if form is posted
if (isset($_POST["submit"]))
{
// set POST to variables (easy to type variable name)
$name = $_POST["name"];
$address = $_POST["address"];
$creditcard = $_POST["creditcard"];
$date = $_POST["date"] == "" ? date("Y-m-d") : $_POST["date"];
$design = $_POST["designType"];
$total = $design; // add the cost of design
$total += $total * 1.08; // work out tax
$total += 5; // the shipping fee
}
?>
I have made a few changes to the form that you posted. Here they are:
I indented the tags (it's a personal preference but I think it makes it look neater)
Added </fieldset> to the end of the form. This ensures it passes W3C Validator which requires closing of tags
I changed the checkboxes to radio types. This was an assumption based on how I thought you form was supposed to be (I wasn't sure where total was coming from otherwise; so I assumed the "Design type" was the price)
I reformatted the <label> and <input> so that they weren't nested (with the exception of radio elements, but that is so you can click the label to select the radio)
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<link rel="stylesheet" href="order.css" />
</head>
<body>
<?php if (isset($_POST["submit"])) { ?><div id="message">Thank you, <?php echo $name; ?> for ordering on <?php echo $date; ?>. The total was <?php echo "$" . number_format($total, 2); ?> </div><?php } ?>
<form name="order" action="complete.php" method="post">
<fieldset>
<legend>Complete Order:</legend>
<h1>Choose Design</h1>
<label>Your Name:</label><input type="text" name="name" />
<label>Address:</label><input type="text" name="address" />
<label>Credit Card #:</label><input type="text" name="creditcard" />
<label>Date:</label><input type="date" id="datepicker" name='date' size='9' value="" />
<br />
<label>Design Types:</label>
<label><img src="1.jpg" alt="$1.00" /><input type="radio" name="designType" value="1" />$1.00</label>
<label><img src="2.jpg" alt="$2.00" /><input type="radio" name="designType" value="2" />$2.00</label>
<label><img src="3.jpg" alt="$3.00" /><input type="radio" name="designType" value="3" />$3.00</label>
<br />
<input type="submit" name="submit" value="Submit Order" />
</fieldset>
</form>
</body>
</html>
That is all.
Again, let me reinforce the idea that Stack Overflow is not here for this type of "question". Please also provide an attempt at your problem as well.

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";
}
?>

Checkbox to act like radio button, check first four or last four checkboxes but not both- javascript?

I am having a problem in javaScript.
I want to check either any of the first 4 checkboxes or any of the last four checkboxes to true.
here in my code if i check any one of the first four or all first four of the checkbox, last four checkboxes are disabled.
now after checking any one or the first four last four are unclickable.
i want them to be clickable and the first four checkboxes to be unchecked.
please correct my code
Here is my code and thanks in advance
<html>
<head>
<title>FooBar</title>
<script language="javascript">
function checkOnly(checked)
{
if(document.myForm.elements[0].checked == true || document.myForm.elements[1].checked == true || document.myForm.elements[2].checked == true || document.myForm.elements[3].checked == true)
{
document.myForm.elements[4].checked = 0;
document.myForm.elements[5].checked = 0;
document.myForm.elements[6].checked = 0;
document.myForm.elements[7].checked = 0;
}
}
</script>
</head>
<body>
<form name="myForm">
<?php for($i=1;$i<=8;$i++){ ?>
<input type="checkbox" name="cb" id="cb" value="1" onClick="checkOnly(this)">
<?php } ?>
</form>
</body>
</html>
Consider using the the 'checked' parameter of you checkOnly function to determine which checkbox the user checked (maybe give them unique ids). As your logic stands now, if you check the first checkbox, it will clear out the checkboxes on the last four. Then if you check the last checkbox, it will still clear out the last four checkboxes because the first checkbox is still checked. This makes it look like the last four checkboxes are disabled even though they aren't.
For example:
<html>
<head>
<title>FooBar</title>
<script language="javascript">
function checkOnly(myCheckbox) {
var checkboxChanged = false;
var checkedTotalValue = 0;
var changedTotalValue = 0;
for(var i = 0; i < document.myForm.elements.length; i++) {
if(document.myForm.elements[i].name != myCheckbox.name) {
if(document.myForm.elements[i].checked == true) {
checkboxChanged = true;
changedTotalValue += parseInt(document.myForm.elements[i].value);
}
document.myForm.elements[i].checked = false;
}
if(document.myForm.elements[i].checked == true) {
checkedTotalValue += parseInt(document.myForm.elements[i].value);
}
}
if(checkboxChanged) {
alert('Checked: ' + checkedTotalValue + ', Changed: ' + changedTotalValue);
}
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name="checkboxGroup1" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup1" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup1" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup1" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup2" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup2" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup2" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup2" id="cb" value="1" onClick="checkOnly(this)">
</form>
</body>
</html>

PHP Forms - Numeric Value of Checkbox

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.

How do I see which checkbox is checked?

How do I check in PHP whether a checkbox is checked or not?
If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.
if (isset($_POST['mycheckbox'])) {
echo "checked!";
}
you can check that by either isset() or empty() (its check explicit isset) weather check box is checked or not
for example
<input type='checkbox' name='Mary' value='2' id='checkbox' />
here you can check by
if (isset($_POST['Mary'])) {
echo "checked!";
}
or
if (!empty($_POST['Mary'])) {
echo "checked!";
}
the above will check only one if you want to do for many than you can make an array instead writing separate for all checkbox try like
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
php
$aDoor = $_POST['formDoor'];
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo htmlspecialchars($aDoor[$i] ). " ";
}
}
Try this
index.html
<form action="form.php" method="post">
Do you like stackoverflow?
<input type="checkbox" name="like" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
form.php
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['like']))
{
echo "<h1>You like Stackoverflow.<h1>";
}
else
{
echo "<h1>You don't like Stackoverflow.</h1>";
}
?>
</body>
</html>
Or this
<?php
if(isset($_POST['like'])) &&
$_POST['like'] == 'Yes')
{
echo "You like Stackoverflow.";
}
else
{
echo "You don't like Stackoverflow.";
}
?>
If you don't know which checkboxes your page has (ex: if you are creating them dynamically) you can simply put a hidden field with the same name and 0 value right above the checkbox.
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
This way you will get 1 or 0 based on whether the checkbox is selected or not.
I love short hands so:
$isChecked = isset($_POST['myCheckbox']) ? "yes" : "no";

Categories