Check if input field empty - javascript

I have used the code below elsewhere in my site and it works. For the life of me I can't understand why it doesn't work here. PROBLEM: keeps throwing alert message.
My HTML:
<form action="processForms.php" method="post" id="joinCommitteeForm" class="headForm shadow">
<div class="outerBlue" style="background:white">
<button type="button" id="cancelForm" class="button" title="Cancel">X</button>
<br><br>
<h3>Get involved—join a committee!</h3>
<?php if(empty($name)||empty($email)||empty($workPhone)){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
<label for="name" style="width:40px">Name</label><input type="text" name="name" id="name"/><br>
<label for="email" style="width:40px" class="clear">Email</label><input type="text" name="email" id="email"/><br>
<label for="phone" style="width:40px;margin-bottom:20px" class="clear">Phone</label><input type="text" name="dayPhone" id="phone"/>
<hr>
<p class="clear">Please select a committee from the list below</p><br><br>
<select name="comName" id="comName" style="width:215px;margin-left:50px;float:left">
<option value="">Select one...</option>
<?php
$sql = mysql_query("SELECT committeeName FROM committeeName ORDER BY committeeName");
while ($row = mysql_fetch_assoc($sql)){
echo "<option value = '".$row['committeeName']."'>".$row['committeeName']."</option>";
}
echo "</select>";?>
<input type="submit" name="submitCommitteeInterest" class="button orange-button clear" value="Submit" style="margin-top:40px"/>
<div class="clear"></div>
<p class="small white" style="line-height:1em;margin-top:20px">NSGP never sells or gives away your personal information</p>
</div>
</form>
My JS:
$("#joinCommitteeForm").submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#name").val()) === "") {
alert('All fields are required');
return false;
}
});

What I suspect the problem is here, is that you are testing if $name or $email is empty, but since you never define them, they will always be empty, per PHP empty() docs: "A variable is considered empty if it does not exist or if its value equals FALSE".
To fix that, you'll need to change your PHP if-statement to:
<?php if(empty($_POST['name'])||empty($_POST['email'])||empty($_POST['dayPhone'])){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
Also, your POST parameter $workPhone doesn't seem to exist in your form. I've changed it to dayPhone here.
The variable $_POST will contain all parameters in the POST request from the form that's submitted.

Related

Form is auto submitting but the data is not getting passed/received

I have a problem in automating a form with hidden inputs in PHP. Basically I'm doing an input for a barcode scanner where the user will input the barcode and it will auto-submit, just like in a cash registry.
The conflict which I think is the cause of the problem is because of a conditional form. Here is a snippet:
<form method="post" id="form1">
<div class="products">
<input type="text" name="code" class="form-control" autofocus required onchange="submit()" />
</div>
</form>
<?php
$query = 'SELECT * FROM product WHERE PRODUCT_CODE='.$code.' GROUP BY PRODUCT_CODE ORDER by PRODUCT_CODE ASC';
$result = mysqli_query($db, $query);
if ($result):
if(mysqli_num_rows($result)>0):
while($product = mysqli_fetch_assoc($result)):
?>
<form id="form2" method="post" action="pos.php?action=add&id=<?php echo $product['PRODUCT_CODE']; ?>" >
<input type="hidden" name="quantity" class="form-control" value="1" />
<input type="hidden" name="name" value="<?php echo $product['NAME']; ?>" />
<input type="hidden" name="price" value="<?php echo $product['PRICE']; ?>" />
<input type="submit" name="addpos" style="margin-top:5px;width: 462px" class="btn btn-info" value="Add"/>
</form>
<?php
endwhile;
endif;
endif;
?>
<script>
function submit() {
document.getElementById("form1").submit();
}
document.getElementById("form2").submit();
</script>
The data from form1 has no trouble auto-submitting, then the form2 will auto-submit but nothing happens. I need help on how can I make form2 auto-submit correctly too. I have tried different event handling for form2 but nothing happens. I only know a little bit of javascript so that's just how my script turned out.
Thank you, Programming kings!
Because the second form is inside the while loop, if there are multiple results there will be multiple forms with the same id = "form2".
You need an increment variable $incrm = 2 inside the loop,
form id='form<?php echo $incrm;?>',
with $incrm++ before ending it. I also recommend to add ann onchange event to the last input 'price' ; onchange = submit(this).
function submit(inp) {
inp.parentElement.submit();
}

How to keep check-boxes checked after form submission

I have 3 check-boxes where I can submit them into MySQL. It inserts perfectly, but the problem is, is when I go back to to edit the game, the check-boxes are not checked at all with their correct values (they are empty).
I know there are a lot of answers on this website about this problem, but I found none of them to work. Maybe its something that Im doing wrong with the code. I will post it here.
THIS IS THE SHORT VERSION OF MY CODE, BECAUSE ITS TOO BIG.
if (isset($_GET['add']) || isset($_GET['edit'])) {
$checkbox = ((isset($_POST['available_consoles']) && $_POST['available_consoles'] != '') ? sanitize($_POST['available_consoles']) : '');
if (isset($_GET['edit'])) {
$checkbox = ((isset($_POST['available_consoles']) && $_POST['available_consoles'] != '') ? $_POST['available_consoles'] : $game['available_consoles']);
}
if ($_POST) {
// Separate ech checkbox value with a SPACE into the database.
$checkbox = implode(', ', $_POST['available_consoles']);
// DO INSERT HERE
}
}
<!-- Add the Add Form -->
<form action="games.php?<?php echo ((isset($_GET['edit'])) ? 'edit='.$edit_id : 'add=1'); ?>" method="post" enctype="multipart/form-data">
<!-------------- AVAILABLE CONSOLES ------------------->
<div class="form-group col-md-6">
<label for="checkbox">Available Consoles: </label>
<label class="checkbox">
<input type="checkbox" <?php if (in_array('Xbox One', $_POST['available_consoles'])) {echo 'checked';} ?> name="available_consoles[]" value="Xbox One">
</label>
<label class="checkbox">
<input type="checkbox" <?php if (in_array('PS4', $_POST['available_consoles'])) {echo 'checked';} ?> name="available_consoles[]" value="PS4">
</label>
<label class="checkbox">
<input type="checkbox" <?php if (in_array('PC', $_POST['available_consoles'])) {echo 'checked';} ?> name="available_consoles[]" value="PC">
</label>
</div>
<div class="form-group pull-right">
Cancel
<input type="submit" value="<?php echo ((isset($_GET['edit'])) ? 'Edit ' : 'Add '); ?> Game" class="btn btn-success">
</div>
</form>
Getting these error message next to checkbox:
Notice: Undefined index: available_consoles in C:\xampp\htdocs\Gamesite\admin\games.php on line 425
Warning: in_array() expects parameter 2 to be array, null given in C:\xampp\htdocs\Gamesite\admin\games.php on line 425
name="available_consoles[]" value="Xbox One">
Getting it for all 3 checkboxes
this is what you need
<input type="checkbox" <?php if (in_array('Xbox One', $_POST['available_consoles'])) {echo 'checked';} ?>id="checkbox" name="available_consoles[]" value="Xbox One">
replace in_array('Xbox One'
with the other consoles names for each input
Here is simple function:
function checked($t,$v){
if (in_array("{$t}", $v)) {
return 'checked';
}
}
use : <?php echo checked('Xbox One',$con); ?>
it was not an array nor was it from $_POST it was actually from the DB so i appended my code to match the answer.

Failure to display result of a php script calculation in the textarea box

I believe that my problem may lie in the way that I am trying to initialize the script. The submit button that I am using seems to just clear the form, and not display any results. I also think there may be a problem with the two lines " $message = $_POST['textarea'];" and "echo $result + $message;" I am not sure if that is the correct way to produce a result into a text area box, as well as display the miles driven and total cost in their separate text boxes. I want this one button to do all three tasks. Is there a way to do this efficiently with PHP?
Edit: Corrected version of the code. Thank you #Fred-ii-!
<?php
if(isset($_POST['submit'])) {
$x = $_POST['beginningOdometerReading'];
$y = $_POST['endingOdometerReading'];
$z = $_POST['daysRentedCar'];
$miles = $y - $x;
$result = (15 * $z) + ($miles * 0.12);
$message = $_POST['textarea'];
echo $result + $message; }
?>
<html>
<head>
</script>
</head>
<body>
<div align="center">
<hr><br>
<form action="index4.php" method="post" name id="Main">
<input type="text" id="name" name="customerName" placeholder="Enter your name here" size="30px">
<br><br>
<input type="text" id="address" name="customerAddress" placeholder="Enter your street address here" size="50px">
<br><br>
<input type="text" id="city" name="customerCity" placeholder="What city do you live in?" size="30px">
<br><br>
<input type="number" id="zip" name="customerZip" placeholder="Enter your zip code" size="30px">
<br><br>
<input type="number" id="bOdometer" name="beginningOdometerReading" placeholder="Start odometer reading" size="80px">
<br><br>
<input type="number" id="eOdometer" name="endingOdometerReading" placeholder="End odometer reading" width="80px">
<br><br>
<input type="number" id="daysRented" name="daysRentedCar" placeholder="Days rented" size="50px">
<br><br>
<input type="submit" id="submit" value="Submit"/>
<br><br>
Miles Driven: <input type="number" id='miles' min="1" max"10000" readonly="" />
Total Cost: <input type="number" id='result' min="1" max"10000" readonly="" />
<br><br>
Summary: <textarea cols="30" rows="2" name="thetextarea" id="textarea"> </textarea>
<br><br>
<input type="reset" value="Reset">
</form>
<hr>
</div>
</body>
There are a few things wrong here.
One of the problems being with your conditional statement:
if(isset($_POST['submit'])) {
it is looking for a named element called "submit" which your submit button is not named.
<input type="submit" id="submit" value="Submit"/>
name it:
<input type="submit" name="submit" id="submit" value="Submit"/>
and you might have been relying on "id" for it. In this instance, you can't.
That is why you're getting back a blank page.
Having used an else{ echo "Error"; } would have echo'd "Error".
For example:
<?php
if(isset($_POST['submit'])) {
$x = $_POST['beginningOdometerReading'];
$y = $_POST['endingOdometerReading'];
$z = $_POST['daysRentedCar'];
$miles = $y - $x;
$result = (15 * $z) + ($miles * 0.12);
$message = $_POST['textarea'];
echo $result + $message; }
else { echo "Error"; }
?>
Then you have
$message = $_POST['textarea'];
but your textarea is named name="thetextarea".
Both of those need to match in names.
You are also using the wrong concatenate operator + for
echo $result + $message;
that needs to be a dot. The + sign is a JS/C++ method of concatenation, if one of those variables contains a string.
echo $result . $message;
or
echo $result . " ". $message;
Had it been a mathematical equation from two variables, then yes; that would have been a valid operator, just not in this case, since you are trying to echo from the $message variable, which is for the "textarea", being "text" and not an integer.
Sidenote: To ensure that you are indeed passing an integer to a POST array, add (int) to it. Example: $x = (int)$_POST['beginningOdometerReading'];
Edit: I found a few more errors in your form.
You have 2x instances of max"10000" it's missing an equal sign max="10000"
and you might be missing name attributes for both of these (which I already outlined are missing = signs for max"10000".
Miles Driven: <input type="number" id='miles' min="1" max"10000" readonly="" />
Total Cost: <input type="number" id='result' min="1" max"10000" readonly="" />
If you're relying on JS as you tagged this as, please edit your question and add that code. However, there was no code in your PHP to support this.
You've a syntax error in <form> being name id="Main"
You will need to adjust your actual code accordingly.
Rewrite:
<?php
if(isset($_POST['submit'])) {
$x = $_POST['beginningOdometerReading'];
$y = $_POST['endingOdometerReading'];
$z = $_POST['daysRentedCar'];
$miles = $y - $x;
$result = (15 * $z) + ($miles * 0.12);
$message = $_POST['thetextarea'];
echo $result . " " . $message; }
else { echo "Error"; }
?>
Error reporting would have signaled an undefined index notice for both of those.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Try to give name for input type `submit` button like
<input type="submit" name="submit" id="submit" value="Submit"/>
And try to remove from action='' because when you submit it directly takes to the index4.php and
error in form statement also you does not provide name you leave it empty like name id="Main"
<form action="index4.php" method="post" name="Main" id="Main">
And use echo statement like
echo $result,$message; }

Required Entry for only one button of two

I have a form that has a text field that is a required entry for one(1) of my two(2) buttons. The first(1st) button applies a code, in the text field, to the products in the cart section of my store. The second(2nd) removes all codes from all products in the cart section.
What's the best way of going about this?
Thx.
<div id="cart-coupon-menu" class="coupon-menu-hide">
<form id="discount-coupon-form" action="<?php echo $this->getUrl('checkout/cart/couponPost') ?>" method="post">
<div class="discount">
<div class="discount-form">
<input type="hidden" name="remove" id="remove-coupone" value="0" />
<div class="input-box">
<input class="input-text" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" placeholder="Enter a Coupon or Promo Code" autocomplete="off"/>
</div>
<div class="buttons-set">
<button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="discountForm.submit(false)" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>
<button type="button" title="<?php echo $this->__('Cancel Coupon') ?>" class="button" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel Coupon') ?>"><span><span><?php echo $this->__('Cancel Coupon') ?></span></span></button>
</div>
</div>
</div>
</form>
</div>
The above form will be serialized and set to a controller via AJAX and an appropriate response will be returned.
When the input box is null I want the input box to act as a required field and disallow submission via the first button. However, when it is null the second button should still allow for submission. When text is entered into the input box they both behave normally.
Currently i'm attempting to do something like this:
<script type="text/javascript">
//<![CDATA[
var discountForm = new VarienForm('discount-coupon-form');
discountForm.submit = function (isRemove) {
if (isRemove) {
$('coupon_code').removeClassName('required-entry');
$('remove-coupone').value = "1";
} else {
$('coupon_code').addClassName('required-entry');
$('remove-coupone').value = "0";
}
if(something where I identify if it is required and the field is null){return null;}
else{continue with ajax call;}
I think it's just a simple javascript something like:
<button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="isValid() ? discountForm.submit(false) : handleInvalid()" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>
I used a ternary operator in there... so basically it says if isValid() returns true, execute: discountForm.submit(false) otherwise execute: handleInvalid().
Then the javascript functions would be:
function isValid() {
var couponCode = document.getElementById('coupon_code').value;
return /* whatever logic you want here... */
}
function handleInvalid() {
// do whatever you want to the coupon_code input to indicate it's required and pop up an error message
alert("Please enter a coupon code!");
}
You should give knockout a try. It updates your view(html) according to changes in your js code. See this example.

Getting values of multiple $_POST elements

I am creating a form that allows the user to supply additional addresses they are located at. I have a drop down that asks "How many additional locations do you have?" based on the number they select I clone the fields "Address, City, State, Zip" and place them directly underneath of each other inside the same form.
What I described above is working but now I am attempting to retrieve the data from these additional fields I added. When the user clicks the submit button the form submits to the same page where I have PHP listening to see if the form has been submitted or not. If it has been submitted I echo the values of the form to the screen.
Now here is the problem. If I leave the dropbox alone so that it is at the default value of "1" fill out the form and click submit I see what I entered. But if I select any other value from the drop down and submit the information from all of the forms I only see the information from the last form and not all of them. Why is this? I have included my code below.
Here is the form :
<form id="blah" method="post">
<div class="Page" id="AdditionalLocations">
<fieldset name="first" class="additional">
<legend>Additional Locations</legend>
<p><label for="Address">Address</label> <input name="Address" type="text" id="Address" /><br /></p>
<p><label for="City">City</label> <input type="text" name="City" id="City" /></p>
<p>
<label for="State">State</label>
<select id="State" name="State">
<option selected="selected">Select your state...</option>
<?php foreach($states as $key=>$value) { ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php } ?>
</select>
</p>
<p><label for="Zip">Zip Code</label><input type="text" name="Zip" maxlength="6" /></p>
<p><label for="Country">Country</label><select id="Country" name="Country">
<option value="US" selected="selected">United States</option>
<option value="CA">Canada</option>
</select></p>
<input type="submit" value="SUBMIT FORM" />
</fieldset>
</div>
</form>
This is how the fields are created based on the dropdown
var cloneIndex = 0,
cloneObj = $('.additional').eq(0);
$(document).on('change', "#NumberOfLocations", function() {
if ( $(this).val() !== "" ) {
for( var x = 2; x < $(this).val(); x++ ) {
$('#AdditionalLocations').append( cloneObj.clone( true ).attr('' ,'data-index', ++cloneIndex) )
}
}
});
This is how I echo the results of the form. It works if I don't create new additional fields based on the drop down.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
var_dump($_POST);
foreach( $_POST as $field ) {
if( is_array( $field ) ) {
foreach( $field as $field2 ) {
echo $field2;
}
} else {
echo $field2;
}
}
}
?>
If I select 2 as the value in the number of locations field this is the html output I get:
<form id="blah" method="post">
<div class="Page" id="AdditionalLocations">
<fieldset name="first" class="additional"></fieldset>
<fieldset name="first" class="additional" data-index="1"></fieldset>
</div>
</form>
Inside the fieldset all of the fields are identical. Why do I not get both fieldsets echoed when I click submit?
UPDATE:
So I changed the names of the second field set by adding a "1" at the end inside the chrome inspector and submitted now I see all of the values I need. So I guess every field in the form has to have a unique name.
your field names should have array notation at the end of their names:
<input type="text" name="City[]" id="City" />
<select id="State" name="State[]">
when php gets these values they will then be in array so you will need to loop over each of the arrays to get the info
for($i=0; $i<count($_POST['City']); $i++){
$city = $_POST['City'][$i];
$state = $_POST['State'][$i];
...
}
There is probably a better way of getting the info out of the arrays, but this is quick and dirty

Categories