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.
Related
I want to call PHP function with the help of JQuery and I also want that Jquery code catch the return type of the calling function for further processing...........
My jQuery code is:
$(document).ready(function(){
$('#ibtn_save').click(function(){
$.post('PHP/newdep.php', { dep_id: newdep.itext_depid.value }, function(result){
if(result == 'exist'){
$('#error_div').html(result).show();
}
});
});
});
My PHP Code is:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$deptid = mysql_real_escape_string($_POST['dep_id']);
$catcher = save_fxn($deptid);
echo $catcher;
}
function save_fxn($ltxt_deptid)
{
$query = "SELECT * FROM table_mstr_department WHERE DeptId='$ltxt_deptid'";
$query_result = mysql_query($query);
if (is_resource($query_result) && mysql_num_rows($query_result) > 0)
{
$sql_result = mysql_fetch_assoc($query_result);
return "exist";
}
else
{
$query = "INSERT INTO table_mstr_department (DeptId, DeptName) VALUES ('$ltxt_deptid','$ltxt_deptname')";
$output = mysql_query($query);
if (!$output)
{
echo "Data not inserted successfully!";
}
return "success";
}
}
?>
and HTML code is as
Please fix the errors below!
<p> <label for="dep_id">Department Id :</label> <input id="itext_depid" name="text_depid" type="text" /> <span class="sdepid"></span> </p>
<p> <label for="dep_name">Deparment Name :</label> <input id="text_depname" name="text_depname" type="text" /> <span class="sdepname"></span> </p>
<input type="submit" id="ibtn_save" name="btn_save" value="Save">
Well, your code seems ok. Since you haven't specified what is not working for you, I'm going to guess that the page reloads as soon as you press your "Save" button, not giving the ajax call the time to complete and to show your result.
This is happening because you use a type=submit button, which will submit your form after completing the onclick handler. The ajax call is performed, but by the time it returns, the calling page has gone.
There are two ways around this. You could change your input to anything beside a type=submit or type=image, for example, you could use:
<input type="button" id="ibtn_save" name="btn_save" value="Save">`
Or, you could have the onclick handler suppress the default action of the submit button, by having it return false:
$(document).ready(function(){
$('#ibtn_save').click(function(){
$.post('PHP/newdep.php', { dep_id: newdep.itext_depid.value }, function(result){
if(result == 'exist'){
$('#error_div').html(result).show();
}
});
return false;
});
});
Does this solve your problem? If not, please do specify what behavior you are encountering, and why you would like it to behave differently.
I have a login form in (login.php). It call a separate sample.php via ajax, and sample.php returns it the value and the Javascript will show the relevant message depending on the php return value. It works perfectly fine in a normal webpage. But when I display the form in color box (in test.php). The javascript/jquery failed to run. I have research abit about this by using ajaxform, but how exactly do i do it? Please advise me some keywords for me to research further :(, i am stucked.
test.php:
$(".ajax").colorbox();
<a href="" class=ajax>Login</a>
This is my ajax function:
function login()
{
hideshow('loading',1);
error(0);
$.ajax({
type: "POST",
url: "http://utourpia.me/php/login_submit.php",
data: $('#loginForm').serialize(),
dataType: "json",
success: function(msg){
if(!(msg.status))
{
error(1,msg.txt);
}
else location.replace(msg.txt);
hideshow('loading',0);
}
});
}
This is my jQuery:
$('#loginForm').submit(function(e) {
login();
e.preventDefault();
});
This is my form:
<form id=loginForm method=post action="">
<label for=email class=email>Email:</label>
<input name=email type=text size=20 maxlength=40/>
<label for="password" class="password">Password:</label>
<input name="password" type="password" size="20" maxlength="40" />
<input class="login" type="submit" name="submit" value="Login" />
</form>
<div id="error"></div>
login_submit.php
<?php
require_once('../lib/connections/db.php');
include('../lib/functions/functions.php');
session_start();
$location_id = $_SESSION['location_id'];
$email = $_POST['email'];
$query = mysql_query('SELECT username FROM users WHERE email = "'.secureInput($email).'"') or die (mysql_error());
if(mysql_num_rows($query) == 1)
{
$row = mysql_fetch_assoc($query);
$username = $row['username'];
}
$returnURL1 = 'http://utourpia.me/php/places.php?id='.$location_id.'&username='.$username;
$returnURL2 = 'http://utourpia.me/php/myprofile.php?username='.$username;
$returnURL3 = 'http://utourpia.me';
$returnURL4 = 'http://utourpia.me/php/dreamtrip.php';
//For login
// we check if everything is filled in and perform checks
if(!$_POST['email'] || !$_POST['password'])
{
die(msg(0,"Email and / or password fields empty!"));
}
else
{
$res = login($_POST['email'],$_POST['password'],$username);
if ($res == 1){
die(msg(0,"Email and / or password incorrect!"));
}
if ($res == 2){
die(msg(0,"Sorry! Your account has been suspended!"));
}
if ($res == 3){
die(msg(0,"Sorry! Your account has not been activated. Please check your email's inbox or spam folder for a link to activate your account."));
}
if ($res == 99){
if ($_SESSION['login_submit']=="places.php")
{
echo(msg(1,$returnURL1));
}
else if ($_SESSION['login_submit']=="myprofile.php")
{
echo(msg(1,$returnURL2));
}
else if ($_SESSION['login_submit']=="home.php")
{
echo(msg(1,$returnURL3));
}
else if ($_SESSION['login_submit']=="dreamtrip.php")
{
echo(msg(1,$returnURL4));
}
}
}
function msg($status,$txt)
{
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
First thing you need to change in the form tag:
Wright only above code. because you have given the method and URL that's why it refresh the page.
Replace your jquery code $('#loginForm').submit(function(e) { this code replace by $('.login').click(function(e) {.
Why are you using the replace method in the ajax success function is gives the error. remove else part.
location object does't have the replace method. if you want to redirect to user on success then use the location.href="your link";.
Make these changes and then check.
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;
}
}
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>
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>