Way to determine if input field has value - php

I'm re-posting this in an attempt to be more specific in my question. I'm trying to combine the calculators found here: http://www.nhpta.com/over-tax-calculator.html.
I'd like the calculate button to be smart enough to know whether or not one of two input fields has a value entered and then perform one of two JS functions, Calculate or Calculate2. If both fields have values entered, I'd like it to throw an error in place of the button instead. This is my concept code below, I don't know how to define the php variables nor do I know how to tell it to look at each input field and determine if there has been a value entered. Also not sure if the print is the right?
<?php
$input_B = "form field named input_B";
$input_C = "form field named input_C";
if($input_B == 'has a value' && $input_C == 'has no value')
{
print ' <P><INPUT TYPE="button" VALUE="Calculate" name="AddButton" onClick="Calculate(this.form.input_A.value, this.form.input_B.value, this.form.input_C.value, this.form)"></P>';
}
elseif($input_C == 'has a value' && input_B == 'has no value' )
{
print ' <P><INPUT TYPE="button" VALUE="Calculate" name="AddButton" onClick="Calculate2(this.form.input_D.value, this.form.input_E.value, this.form.input_F.value, this.form)"></P>';
}
elseif ($input_C == 'has a value' && input_B == 'has a value')
{
print ' Please choose only one field to fill in';
}
else
{
print ' <P><INPUT TYPE="button" VALUE="Calculate" name="AddButton" onClick="Calculate(this.form.input_A.value, this.form.input_B.value, this.form.input_C.value, this.form)"></P>';
} // End if/else if
?>

The first if statment should be rewritten like this :
if(($input_B != "") && ($input_C == ""))
Then the logic is the same for the others

As long as the two input fields have (unique!) ids, you can do something like this:
var field0 = document.getElementById("field0id").value;
var field1 = document.getElementById("field1id").value;
if(field0 === ""){
if(field1 !== ""){
calculate();
}else{
//error
}
}elseif(field1 === ""){
calculate2();
}else{
//error
}

First of all, you shouldn't need to do anything server-side for this (that's where PHP runs). Instead use javascript. It should look something like this: (Bear in mind that this is using jQuery, which is a javascript library. You can learn about jQuery here.)
<label for="input1">Input 1</label>
<input type="text" name="input1" id="input1" /><br />
<label for="input2">Input 2</label>
<input type="text" name="input2" id="input2" /><br />
<input type="submit" value="Submit" id="submit" onclick="calculate();" <!-- you only need the onclick attribute if you're not using jQuery --> />
Edit: functions modified to perform the logic as defined in the question
<!-- pseudo-code with jQuery -->
<script language="javascript" type="text/javascript">
$("#submit").on('click', function() {
var input1Val = $("#input1").val();
var input2Val = $("#input2").val();
if (input1Val != "" && input2Val != "") {
alert("You may only enter a value in one input field.");
} else if (input1Val != "") {
calcFunc1(input1Val);
} else if (input2Val != "") {
calcFunc2(input2Val);
} else {
alert("You must enter a value in one of the input fields.");
}
});
</script>
<!-- pseudo-code with straight javascript -->
<script language="javascript" type="text/javascript">
function calculate() {
var input1Val = document.getElementById("input1").value;
var input2Val = document.getElementById("input1").value;
if (input1Val != "" && input2Val != "") {
alert("You may only enter a value in one input field.");
} else if (input1Val != "") {
calcFunc1(input1Val);
} else if (input2Val != "") {
calcFunc2(input2Val);
} else {
alert("You must enter a value in one of the input fields.");
}
}
</script>

Related

PHP/JavaScript form validation?

I'm new with PHP and JavaScript. I eant to validate form, and if the form input fields are correct, then send it to php external script. I've tried something like this:
<head>
<script type="text/javascript">
function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
alert("Input name!");
} else if(y==null || y=="") {
alert("Input surname!");
} else if(z==null || z=="") {
alert("Input age!");
} else {
// IS IT POSSIBLE TO SEND FORM HERE FORM VARIABLES TO PHP SCRIPT?
}
}
</script>
</head>
<body>
<form name="forma" action="validate.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
Since you are not returning false from your function, the form should be being submitted anyway. You can stop it from being submitted by having your validate() function return false.
Your code looks correct, other than the fact you probably want to return false on failure to prevent the form from submitting. When not returning false, the form will simply continue to submit.
I also think you probably meant to name your form form not forma
You should validate the input server-side (php), even if you did it client-side (javascript).
You do this by checking on $_POST in validate.php:
Quite at the beginning of your script:
if (isset($_POST)) { // form has been sent
if (!isset($_POST['firstname']) || strlen($_POST['firstname'])==0) { // no entry
$e['firstname']='please enter a firstname!'; // prepare error-msg
}
if (!isset($e)) { // no error, continue handling the data
// write data to database etc.
}
}
// in your form...
if (isset($e)) echo "there were errors: ". implode(',',$e);
You need to put this code:
function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
alert("Input name!");
return false;
} else if(y==null || y=="") {
alert("Input surname!");
return false;
} else if(z==null || z=="") {
alert("Input age!");
return false;
} else {
return true;
}
}

Problems with javascript validation in PHP document

I have this .php document where you can register on a webshop. I want to add javascript validation to it, but the site is made of .php completely, so no html head and body tags. Normally you can put the javascript source in the head tag, but in the .php you can't. (or at least i don't know how)
When testing the code, the javascript document seems fine, but when i put it in the .php document it gives certain errors about (") and ('). When i try to link to the seperate javascript document, the code doesn't seem to work at all.
(i've added the whole php page) Php document begin:
<?php
include 'header.php';
include 'menu.php';
echo '
function checkEmail(myForm)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(registration.emailAddress.value))
{
return (true)
}
alert("Invalid E-mail Address! Please re-enter.")
return (false)
}
function validatePwd()
{
var invalid = " "; // Spatie mag niet
var minLength = 6; // Minimaal 6 tekens
var pw1 = document.registration.password.value;
var pw2 = document.registration.passwordConfirm.value;
// Beide velden gelijke waarde
if (pw1 == "" || pw2 == "")
{
alert("Please enter your password twice.");
return false;
}
// Minimale lengte variabele
if (document.registration.password.value.length < minLength)
{
alert("Your password must be at least " + minLength + " characters long. Try again.");
return false;
}
// spatiegebruik variabele
if (document.registration.password.value.indexOf(invalid) > -1);
{
alert("Spaces are not allowed.");
return false;
}
else
{
if (pw1 != pw2)
{
alert ("You did not enter the same new password twice. Please re-enter your password.");
return false;
}
else
{
return true;
}
}
}
<div id="main">
<form name="registration" action="registerconfirm.php" method="post" id="form" onSubmit="return validatePwd()">
<h2>Personal Information</h2>
<fieldset class="login_register">
<label for="firstName" class="form">First name:</label>
<div class="registrationForm" id= "firstNameCheck"></div>
<input type="text" name="firstname" id="register_first_name"/>
<label for="lastName" class="form">Last name:</label>
<div class="registrationForm" id="lastNameCheck"></div>
<input type="text" name="lastname" id="register_last_name"/>
<label for="email" class="form">E-mail:</label>
<div class="registrationForm" id="emailCheck"></div>
<input type="text" name="emailAddress" id="register_email"/>
</fieldset>
<h2>Login Information</h2>
<fieldset class="login_register">
<label for="password" class="form">Password:</label>
<div class="registrationForm" id="lastNameCheck"></div>
<input type="password" name="password" id="password"/>
<label for="passwordCheck" class="form">Confirm password:</label>
<div class="registrationFormAlert" id="divPassCheck"></div>
<input type="password" name="passwordConfirm" id="passwordConfirm"/>
<input type="submit" class="button" value="SUBMIT"/>
</fieldset>
</form>
</div>
';
include 'footer.php';
?>
and the Javascript code:
<SCRIPT LANGUAGE="JavaScript">
function checkEmail(myForm)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(registration.emailAddress.value))
{
return (true)
}
alert("Invalid E-mail Address! Please re-enter.")
return (false)
}
function validatePwd()
{
var invalid = " "; // Invalid character is a space
var minLength = 6; // Minimum length
var pw1 = document.myForm.password.value;
var pw2 = document.myForm.passwordConfirm.value;
// check for a value in both fields.
if (pw1 == '' || pw2 == '')
{
alert('Please enter your password twice.');
return false;
}
// check for minimum length
if (document.myForm.password.value.length < minLength)
{
alert('Your password must be at least ' + minLength + ' characters long. Try again.');
return false;
}
// check for spaces
if (document.myForm.password.value.indexOf(invalid) > -1)
{
alert("Sorry, spaces are not allowed.");
return false;
}
else
{
if (pw1 != pw2)
{
alert ("You did not enter the same new password twice. Please re-enter your password.");
return false;
}
else
{
return true;
}
}
}
A couple of things: you can add a <script> tag anywhere you like. The attribute language, though, doesn't really exist, but that's not that important. All the same, it should be <script type="text/javascript">.
If your site is the output of (a bunch of) PHP scripts, why not simply echo the script?
echo '<script type="text/javascript" src="path/to/script.js"></script>';
Or, in the header file:
echo '<title>Title</title>';
?>
<script type='text/javascript'>
var script ='just add it here';
</script>
<?php
echo '</head>';//continue php
There's nothing preventing you to do this, either.
JavaScript is executed in the client's browser (aka, client-side), PHP is a server-side language.
Unless you plan on writing a JS interpreter for PHP, you can't run JS from PHP.
A better option would be to re-write the JS in PHP.
Unless you're having trouble including the file, then you'll just have to edit a:
<script type="text/javascript" src="myJSFile.js"></script> tag into your header.php.
So:
echo '<script type="text/javascript" src="myJSFile.js"></script>';
Try using PHPs HEREDOC Syntax to output the function.
http://www.php.net/manual/it/language.types.string.php#language.types.string.syntax.heredoc

jQuery focus / blur $_GET['variable'] conflict

I have a simple focus / blur. 'Name of Venue' is shown by default since it's the value of the input type. on 'focus' it hides and on 'blur' is shows again if there's no text.
Here's the input field
<input type="text" name="name" id="search_name" value="Name of Venue" maxlength="100" />
Here's the jQuery
$('#search_name').focus(function() {
if($(this).val() == 'Name of Venue') {
$(this).val('');
}
});
$('#search_name').blur(function() {
if($(this).val() == '') {
$(this).val('Name of Venue');
}
});
On submit I don't want 'Name of Venue' to be stored as the get variable for $_GET['name']. So, I'm doing <br /><br /> PHP
if($_GET['name'] === 'Name of Venue') {
$_GET['name'] = '';
}
But, this doesn't work. How can I make it so the get variable will be empty on submit if it's the default value?
Consider using the HTML5 placeholder attribute if possible. The value will be blank if nothing was entered.
<input type="text" name="search_name" id="search_name" placeholder="Name of Venue" maxlength="100" />
It will appear/disappear automatically, so you won't need the focus/blur code. Also, "name" is a bad name for name, I'd use something more unique (usually the id will do).
As an alternative, you could do this:
<form id="myform" method="get" action="">
<input type="text" name="search_name" id="search_name" value="Name of Venue" maxlength="100" />
<input type="submit" id="submit_button" value="Submit" />
</form>
<script src="jquery-1.7.1.min.js"></script>
<script>
// ready() not need if <script> follows content, but best to put this in a .js file and link in <head>
$(document).ready(function() {
// Define once and you're good
var search_name = $('#search_name');
var submit_button = $('#submit_button');
var search_default = 'Name of Venue';
search_name.focus(function() {
if($(this).val() == search_default) {
$(this).val('');
}
});
search_name.blur(function() {
if($(this).val() == '') {
$(this).val(search_default);
}
});
$("#myform").submit(function(event) {
if (search_name.val() == '' || search_name.val() == search_default) {
event.preventDefault();
} else {
return true;
}
});
});
</script>
<?php
var_dump($_GET);
$name = '';
if (isset($_GET['search_name'])) {
// Without the check, we might run query when none exists
$name = $_GET['search_name'];
$name = $name != 'Name of Venue' ? $name : '';
}
var_dump($name);
?>
This will prevent a submit with a blank or default name. It's probably handy to put any repeated logic in a function and call those when handling the GET in PHP with any extra search variables.
You can control the value on client side and if it's a required field don't let the form to be submitted. If it's not required, just set the value to "" if it is "Name of Venue".
I think you have to make the field value blank before submitting the form if value is Name of Venue.
$('#frName').submit(function() { if($('#search_name').val() == 'Name of Venue' ){ $('#search_name').val('') } return false;});
You can remove return false if you want to submit the value. Hope its helps you

how to see a checkbox is not checked

I want to alert user if they haven't checked any checkbox, and return to the form
After they checked at least one checkbox, proceed into the next page
How can I do that ?
<input type="checkbox" name="pay[]" value="
<?php
echo $DateArr[$record_count].";";
echo $invoiceArr[$record_count].";";
echo $TotalArr[$record_count].";";
echo $amount_dueArr[$record_count];
?>
" onClick="checkTotal()"/>
<td ALIGN="right" ><input type="submit" name="submit" value="Continue" onMouseOver="CheckBoxStatus()"></td>
javascript :
function CheckBoxStatus()
{
var checkbox_status = document.getElementsByName("pay[]").value;
if (checkbox_status = ";;;")
{
alert("Please select at least one to proceed!");
return false;
}
else
{
alert("Continue!");
return true;
}
}
If user hasn't checked, at least one checkbox, alert the message and return to form
Then
<form name="payform" method="POST" action="payment.php" onSubmit=" CheckBoxStatus()">
How can I stay in the form if user is not checking any checkboxes ?
May be like this :
function CheckBoxStatus()
{
if (document.getElementsByName("pay[]").checked == true)
{
document.forms["payform"].submit();
return true;
}
else
{
alert("Please select at least one invoice to proceed!");
document.forms["payform"].reset();
return false;
}
}
can i do like this :
`
function CheckBoxStatus()
{
var status=$("pay[]").attr('checked');
if (status=true)
{
//if(document.getElementsByName("pay[]").checked) {
return true;
}
else {
alert("Please select at least one to proceed!");
return false;
}
}`
With jQuery
var $checked = $("input:checked");
if($checked.length == 0) {
alert("Please select at least one to proceed!");
}
That HTML is a bit of a mess. A couple of things...
Get rid of the <td> tag containing the button. It doesn't look like it has a purpose.
To call the JavaScript you need to use onsubmit not onMouseOver.
To check if the checkbox is checked change your function to the following.
function checkBoxStatus {
if(document.getElementsByName("pay[]").checked) {
return true;
}
else {
alert("Please select at least one to proceed!");
return false;
}
}
EDIT; forgot the alert
Check if you have included jquery. :|
Try this:
<input id="ipay" type="checkbox" name="pay[]" value="
<?php
echo $DateArr[$record_count].";";
echo $invoiceArr[$record_count].";";
echo $TotalArr[$record_count].";";
echo $amount_dueArr[$record_count];
?>"
/>
<td ALIGN="right" ><input type="submit" name="submit" value="Continue"></td>
<form id="pform" name="payform" method="POST" action="payment.php">
Javascript:
$(document).ready(function() {
$('#pform').submit(function(e) {
var paycheck = $('#ipay').attr('checked');
if(paycheck != true or paycheck != 'checked') {
alert('Please check at least one option.');
e.preventDefault();
}
});
});
You can do something like this:
<html>
<head>
<title>Verify Checkbox</title>
<script type="text/javascript">
function verifyCheckboxSelected(form) {
var theForm = document.forms[form];
var valid = false;
for( var i=0; i < theForm.length; i++ ) {
if(theForm.elements[i].checked) {
valid = true;
}
}
if (!valid) {
alert('You must select at least one checkbox')
return false;
}
}
</script>
</head>
<body>
<form name="myForm" onSubmit="return verifyCheckboxSelected(this.name)">
<input type="checkbox" name="myCheckBoxes[]"/>Checkbox A</br>
<input type="checkbox" name="myCheckBoxes[]"/>Checkbox B</br>
<input type="checkbox" name="myCheckBoxes[]"/>Checkbox C</br>
<input type="submit" value="submit" />
</form>
</body>
</html>

reset Function displayed data in form

function my_fav_quote_show_optin_form() {
if (!empty($_POST['my_fav_quote_email'])) {
my_fav_quote_opt_in();
}
$out2 = '';
$out = '<form action="" method="post" id="requestQuote">';
$out .= '<table style="padding="0px" width="40px">';
$out .= '<tr><td style="vertical-align: middle;">Message:<br></td><td><textarea placeholder="" name="my_fav_quote_message" id="my_fav_quote_message"></textarea></td></tr>';
$out .= '';
$out .='<tr><td colspan="2">';
if ( function_exists( 'my_fav_quote_display' ) ){
$out .= my_fav_quote_display();
}
if ( function_exists( 'my_fav_quote_display3' ) ){
$out .= my_fav_quote_display3();
}
$out .='</td></tr>';
$out .= '<tr><td colspan=2 align=center><input type="submit" value="Request Quote" onclick="return chk_validation()" style="background-color:#000;color:#FFF;padding:5px;margin-top:10px;border:none;cursor:pointer;"/> <input type="button" onclick="formReset()" value="Reset form" /></td></tr>';
$out .='</table></form>';
echo $out;
?>
<script language="javascript" type="text/javascript">
function formReset()
{
document.getElementById("requestQuote").reset();
}
//<![CDATA[
function validate_email(field,alerttxt)
{
apos=field.indexOf("#");
// alert(apos);
dotpos=field.lastIndexOf(".");
//alert(dotpos);
if (apos<1||dotpos-apos<2)
{ return false;}
else {return true;}
}
function chk_validation()
{
if(document.getElementById("my_fav_quote_name") && document.getElementById("my_fav_quote_name").value == '')
{
alert("Please Enter Name");
document.getElementById("my_fav_quote_name").focus();
return false;
}
if(document.getElementById("my_fav_quote_email").value == '')
{
alert("Please Enter Email");
document.getElementById("my_fav_quote_email").focus();
return false;
}
else
{
//alert(validate_email(document.getElementById("my_fav_quote_email").value,"Not a valid e-mail address!");
if (validate_email(document.getElementById("my_fav_quote_email").value,"Please enter valid e-mail address!")==false) {
alert("Please enter valid e-mail address!");
document.getElementById("my_fav_quote_email").focus();
return false;
}
}
if(document.getElementById("security_code").value == '')
{
alert("Please Enter Security Code");
document.getElementById("security_code").focus();
return false;
}
if(document.getElementById("quotes").value == '')
{
alert("Please add atleast one request quote");
document.getElementById("quotes").focus();
return false;
}
//return true;
}
//]]>
</script>
<?php
}
this is a form of one of the wordpress plugin written in php i need to added a reset button for which i tried with
function formReset()
{
document.getElementById("requestQuote").reset();
}
but that was not working
Wordpress Plugin Usage link
I want to reset the form when the user click on reset button all the data that is displayed should be removed from all the feilds and from
from (the two functions my_fav_quote_display3 &the my_fav_quote_display & ) which was not actually happening.
In what why I can do that ?
Your reset() call successfully resets the form, which is exactly what it you wanted it to do.
The problem is that there's more than just a form to clear: You seem to be using a plugin, which provides both the my_fav_quote_display() functions. There is really no way to tell what these methods do, nor which, if any, fields in your database are used by this plugin, because you haven't shown any of the relevant code (nor even mentioned the plugin's name).
For the quotes to disappear permanently, you need to look at your plugin's API and find out how my_fay_quote_display() and my_fav_quotes_display3() work, and if there is a data field you can reset, or some other way to stop them from being shown.
You can simply reset a form with a reset type button.
<input type="reset" value="Reset">
<input type="button" onclick="formReset()" value="Reset form" />
HTML have reset button, you dont need javascript for it.
<input type="reset" value="Reset form" />
If you really wanna do it with javascript you could do something like:
<form name="myform"></form>
<script> document.myform.reset() </script>
Use the name tag instead of id and it should work, did for me at least.

Categories