Ajax-PhP communication - javascript

I am having a problem with a script i am programming. I am very new to AJAX, and can't figure out what i am doing wrong that makes it not to work. Any help would be highly appreciated. I have multiple forms on the page and when i separate the forms the communication between the Ajax and php works just fine. But when i put everything together, it stops working. I do believe its either a communication problem or maybe some conflicting scripts or just some bad coding.
Here is the php code:
#session_start();
if(isset($_SESSION["username"])){
header("location: home.php");
exit();
}else{
$usertitle = $_POST['ut'];
$userfname = $_POST['uf'];
$userlname = $_POST['ul'];
$useremail = $_POST['ue'];
$userloc = $_POST['uloc'];
$user_est_typ = $_POST['utp'];
$userfname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userfname);
$userlname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userlname);
if($usertitle == "Title...."){
echo '<font color="red">Error: Please select a title.';
exit();
}else if($userfname == NULL){
exit('<font color="red">Error: You need a first name to proceed. </font>');
}else if( strlen($userfname) <= 2){
exit('<font color="red">Error: First name should be three (3) or more letters.</font>');
} else if($userlname == ""){
exit('<font color="red">Error: Giving a Surname would be nice.</font>');
}else if( strlen($userlname) <= 2){
exit('<font color="red">Error: Surname should be three (3) or more Letters.</font>');
}else if(!strpos($useremail, "#") || !strpos($useremail, "." || !filter_var($useremail, FILTER_VALIDATE_EMAIL) === true)){
exit('<font color="red">Email Address not valid</font>');
}else if($user_est_typ == "Select..."){
exit('<font color="red">Error: You must select an estimate type to proceed.</font>');
}else if($userloc == ""){
exit('<font color="red">Error: A location would be required so as to get the radiation data for the estimates</font>');
}else {
include("../../scripts/dbconect.php");
$queryuseremail = mysql_query("SELECT id FROM userdata WHERE userEmail='$useremail' LIMIT 1");
$useremail_check = mysql_num_rows($queryuseremail);
if ($useremail_check > 0){
echo "The email address ".$useremail." is already registered in ur database";
exit();
}
// More Validation and mysql insert
exit('<font color="red">signup_success</font>');
}
}
Here is my AJAX codes:
function _(x){
return document.getElementById(x);
}
function show(id){
var divelement = _(id);
if(divelement.style.display == 'none')
divelement.style.display = 'block';
else
divelement.style.display == 'none';
}
function hide(id){
var divelement = _(id);
if(divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display == 'block';
}
function emptyElement(id){
_(id).innerHTML = "";
}
function estimatetypeimg(){
var estType = _('estimatetype').value;
if (estType == 'solarpv'){
show('estimate_pv');
hide('estimate_thermal');
}
else if(estType == 'solarthermal'){
hide('estimate_pv');
show('estimate_thermal');
}
else{
hide('estimate_pv');
hide('estimate_thermal');
}
}
function newUsers() {
var title = _("salutation").value;
var fname = _("fname").value;
var lname = _("lname").value;
var email = _("email").value;
var loc = _("location").value;
var tp = _("estimatetype").value;
var url = "ajax.php";
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
_("statuscheck").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(vars);
}
And here is my html code:
<div id="startbuts" style="display:none">
<form class="pure-form" name="startbutsform" id="startbutsform" onsubmit="return false;">
<button type="submit" id="newusersbtn" onclick="show('newusers'); hide('existingusers'); hide('existingusersbtn');"class="pure-button pure-button-primary">New Estimate</button>
<button type="submit" id="existingusersbtn" onclick="show('existingusers'); hide('newusers'); hide('newusersbtn');" class="button-secondary pure-button">Load Previous Estimate</button>
</form>
<div id="existingusers" style="display:none">
<form class="pure-form" name="signupex" id="signupex" onsubmit="return false;">
<fieldset>
<legend>Existing users: login with your email and Data ID.</legend>
<input type="email" id="dataemail" placeholder="Email" >
<input type="text" id="dataid" placeholder="DataId"><br/>
<button id="signupexbtn" type="submit" onclick="signinold()" class="pure-button pure-button-primary">Sign in</button>
</fieldset>
</form>
</div>
<div id="newusers" style="display:none">
<form class="pure-form" name="signupnew" id="signupnew" onsubmit="return false;">
<fieldset>
<legend>New users start here.</legend>
<div class="pure-control-group">
<label for="salutation">Title: </label>
<select id="salutation" name="salutation">
<option>Title....</option>
<option>Prof. Dr.</option>
<option>Prof.</option>
<option>Dr.</option>
<option>Mr.</option>
<option>Mrs.</option>
<option>Miss.</option>
</select>
</div>
<div class="pure-control-group">
<label for="fname">First name:</label>
<input id="fname" name="fname" type="text" placeholder="First Name">
</div>
<div class="pure-control-group">
<label for="lname">Last name:</label>
<input id="lname" name="lname" onfocus="emptyElement('errorcheck')" type="text" placeholder="Last Name">
</div>
<div class="pure-control-group">
<label for="email">Email Address:</label>
<input id="email" name="email" type="email" onfocus="emptyElement('errorcheck')" placeholder="Email Address">
</div>
<div class="pure-control-group">
<label for="location">Project Location: </label>
<input id="location" name="location" type="text" onfocus="emptyElement('errorcheck')" placeholder="Enter City ex Buea...">
</div>
<div class="pure-control-group">
<label for="estimatetype">Type of Estimate: </label>
<select id="estimatetype" name="estimatetype" onchange="estimatetypeimg()">
<option value="Select">Select...</option>
<option value="solarpv">Solar PV</option>
<option value="solarthermal">Solar Thermal</option>
</select>
</div>
<div id="estimate_pv" style="display:none" >
<img id="solarpvimg" src="images/solarpv.png" width="250" height="109" alt="Solar PV" />
</div>
<div id="estimate_thermal" style="display:none">
<img id="solarthermalimg" src="images/solarthermal.png" width="250" height="109" alt="Solar PV" />
</div>
<hr/>
<button id="signupnewbtn" type="button" class="pure-button pure-button-primary" onclick="newUsers()" >Start Calculator</button>
<button onclick="emptyElement('errorcheck'); hide('estimate_pv'); hide(estimate_thermal);" class="pure-button pure-button-primary" type="reset">Reset </button>
</fieldset>
</form>
</div>
</div>

Thank you David Lavieri and especially Sher Kahn. Your responses got me thinking and i finally figured out why I was not getting any response from my PhP script. As Khan also mention, I am just a hobby coder and you are absolutely right my code is not very clean. I cleaned the code on JSLint and realised i had too many bad coding habits. :). Thanks also for giving me a heads up with malsup query plugins. they are very handy and will help a lot.
So finally to the problem I had. The actual problem was the link to the php file. The url was poorly defined which made it impossible for the communication between the ajax and the php file. I use Dreamweaver and when i used the browse tool it gave me a link to the file, but because my javascript was external, the link was only relative to the Javascript file, and not the main html file. Also when i double checked my data vars, i missed and "&" for my second variable in the string before "uf"
var url = "ajax.php";// i changed the path file to scripts/ajax.php and it worked like magic.
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// before
var vars = "ut="+title+"&uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// After
Hope this can be of help to someone else.
regards and thanks David and Khan.

Related

Javascript document.getElementById function not returning checkbox value to HTML form

I have been searching for an answer everywhere but just can not find what I need.
I have a webpage that has an HTML table on the left column and an HTML form on the right column. When I click on a row in the table on the left I want it to display the values in the form on the right.
I have this working perfectly for the text fields on the form, but not for the two checkboxes. My javascript will return either true or false or checked and unchecked to the document.getElementById within the script itself by using alert(); but I have no idea what it needs to allow the checkboxes to display these values. I thought the document.getElementById would return the values but it seems it does not.
I have tried all kinds of conveluted ways to get this to work but can not seem to get the correct code needed.
I am new to all this so there is most likely something really simple I am missing.
This is the HTML form code:
<div class="column right">
<table>
<tr></tr>
<tr>
<div class="lockinv">
<form autocomplete="off" name="lockform" class="keyassign" action="includes/lockinventory.inc.php"
method="post">
<label id="inventory" for="locknum">Lock Number</label>
<input id="invlocknum" type="text" name="locknum" value="" required>
<label id="inventory" for="locktype">Lock Type</label>
<input id="invlocktype" type="text" name="locktype" value="" required>
<label id="inventory" for="keycode">Key Code</label>
<input id="invkeycode" type="text" name="keycode" value="" required>
<label id="inventory" for="lockengraved">Lock Engraved</label>
<input id="invlockengraved" type="hidden" name="lockengraved" value="0">
<input id="invlockengraved" type="checkbox" name="lockengraved" value="1">
<label id="inventory" for="lockmastered">Lock Mastered</label>
<input id="invlockmastered" type="hidden" name="lockmastered" value="0">
<input id="invlockmastered" type="checkbox" name="lockmastered" value="1">
<label id="inventory" for="locknote">Lock Note</label>
<textarea id="inventorynote" name="locknote" rows="5" cols="60"></textarea>
<div class="wheel">
<?php
if (isset($_GET["error"])) {
if($_GET["error"] == "lockexists") {
echo "<p>Lock Already In Inventory!</p>";
}
else if ($_GET["error"] == "lockexistsfailed") {
echo "<p>Lock Already In Inventory!</p>";
}
}
?>
</div>
<input id="bt6" type="submit" name="submit" value="Save">
<button id="bt6" type="reset" name="button">Cancel</button>
</form>
</div>
</tr>
</table>
</div>
This is my JavaScript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript"></script>
<script>
$(function () {
$('#lockTable td').click(function () {
var currentRow = $(this).closest("tr");
var locknum = currentRow.find("td:eq(0)").text();
var locktype = currentRow.find("td:eq(1)").text();
var keycode = currentRow.find("td:eq(2)").text();
var engraved = currentRow.find("td:eq(3)").find(":checkbox");
var mastered = currentRow.find("td:eq(4)").find(":checkbox");
var locknote = currentRow.find("td:eq(5)").text();
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
$grved = "checked";
} else {
$grved = "unchecked";
}
var lockmastered = mastered.prop("checked");
if (lockmastered === true) {
$msted = "checked";
} else {
$msted = "unchecked";
}
document.getElementById('invlocknum').value = locknum;
document.getElementById('invlocktype').value = locktype;
document.getElementById('invkeycode').value = keycode;
document.getElementById("invlockengraved").value = $grved;
document.getElementById('invlockmastered').value = $msted;
document.getElementById('inventorynote').value = locknote;
alert(document.getElementById("invlockengraved").value);
alert(document.getElementById("invlockmastered").value);
});
});
</script>
<p id="invlocknum"></p>
<p id="invlocktype"></p>
<p id="invkeycode"></p>
<p id="invlockengraved"></p>
<p id="invlockmastered"></p>
<p id="invlocknote"></p>
<p id="info"></p>
<p id="result"></p>
I found the answer to my issue. I had to modify my if statement in the Javascript to the following. Works the way I want it to. Thanks to all that helped.
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
document.getElementById("invlockengraved").checked = lockengraved;
}else if (lockengraved === false) {
document.getElementById("invlockengraved").checked = lockengraved;
}

validate email and display accordingly

I want to check the email validity in Javascript and then show alert box if its invalid and if valid then show the div2. But its not working
Here is javascript:
function _(x){
return document.getElementById(x);
}
function Phase1()
{
myemail = _("email").value;
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (reg.test(designeremail) == false)
{
alert('Invalid Email Address');
}
else
{
_("phase1").style.display = "none";
_("phase2").style.display = "block";
}
}
Here is my html:
<form id="myform" onsubmit="return false" >
<div id="phase1">
<label>Email</label><div><input type="text" id="email" name="email" required></div>
<div><button onclick="Phase1()" class="btn"><strong>Next</strong></button></div>
</div>
<div id="phase2">
<label>Name</label><div><input type="text" id="mname" name="myname" required></div>
<div><button onclick="Phase2()" class="btn"><strong>Submit</strong></button></div>
</div>
</form>
but even with wronng email it proceeds and shows the phase2
I think this is js and not php. Btw, it's because probably you're testing on the wrong variable:
if (reg.test(designeremail) == false)
you're testing designeremail, which is different from email from the form which probably you wanted test against to.

Enable radio button only for admin user

In the application I'm developing I have an admin panel in that panel there a function to create, edit and delete users.
In the form I create 3 user types using a while loop which drags data from a database and the 3 user types are:
Admin
Manager
User
HTML Form:
<?php
/**
* Created by PhpStorm.
* User: SiNUX
* Date: 4/6/2017
* Time: 3:41 PM
*/
session_start();
include_once("../iConnect/handShake.php");
$getUserRole = "SELECT * FROM userroles ORDER BY urId ASC";
$getUserRoleQuery = $dbConnect -> query($getUserRole);
?>
<html>
<head>
<title>Timer User Creation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Style Sheets -->
<link rel="stylesheet" type="text/css" href="../../CSS/main.css">
<!-- Java Scripts -->
<script language="JavaScript" type="text/javascript" src="../../jScripts/jquery-3.2.0.min.js"></script>
<script language="javascript" type="text/javascript" src="../../jScripts/svrTimeDate.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/reload.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/setMsg.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/userCreatFunctions.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/multiScript.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/getIds.js"></script>
</head>
<body onload="pauseLoad4()">
<div id="divCenter" class="box">
<label id="userName">Hello <?php echo $_SESSION["fName"]." ".$_SESSION["lName"]; ?></label><br><br>
<label id="uId" hidden>1</label>
<div style="width: 166px; position: absolute; left: 642px; top: 20px; height: 44px;">
<img src="../../images/logo.png" width="142" height="33">
</div>
<label for="date">Date:</label>
<label id="date" style="margin-left: 50px;"></label><br><br>
<label for="fName">First Name:</label>
<input type="text" id="fName" name="fName" style="margin-left: 10px;" onkeyup="checkEmpty();">
<label for="lName" style="margin-left: 8px;">Last Name:</label>
<input type="text" id="lName" name="lName" style="margin-left: 10px;" onkeyup="checkEmpty();" disabled>
<label for="uName" style="margin-left: 8px;">User Name:</label>
<input type="text" id="uName" name="uName" style="margin-left: 7px;" onkeyup="checkEmpty();" disabled><br><br>
<label for="pWord1" style="margin-left: 8px;" >Password:</label>
<input type="password" id="pWord1" name="pWord1" style="margin-left: 17px;" onkeyup="checkLength();" disabled>
<label for="pWord2" style="margin-left: 8px;">Confirm Password:</label>
<input type="password" id="pWord2" name="pWord2" style="margin-left: 8px;" onkeyup="checkPass();" disabled>
<label for="uTeam" style="margin-left: 8px;">Team</label>
<select name="uTeam" id="uTeam" style="width: 170px;" onchange="teamId(this.id);enableRoles();" disabled>
<option></option>
</select>
<input type="text" name="uTeamId" id="uTeamId" hidden><br><br>
<div id="userRoles">
<label for="userRoles">User Role:</label><label for="uAttrib" style="margin-left: 250px;">User Attributes:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" class="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>"
<?php if ($_SESSION["uRole"] != "1" && $row["userRole"] == "Admin" ){?> disabled <?php } ?>><?php echo $row["userRole"]; }?>
<input type="checkbox" id="tl" name="tl" value="yes" style="margin-left: 120px;" disabled>Team Leader
</div>
<label id="msgID" hidden></label>
<div id="msg"></div>
<div id="sbmBtns">
<input type="button" value="Reset" name="reset" id="reset" class="btn" onclick="resetForm()">
<input type="button" value="Submit" name="submit" id="submit" class="btn" onclick="pauseLoad3();" disabled>
</div>
</div>
</body>
</html>
I use a JavaScript to validate the form and to enable the next text box if the validation criteria is met.
JavaScript:
function checkEmpty() {
var msg = document.getElementById('msg'),
fName = document.getElementById('fName'),
lName = document.getElementById('lName'),
uName = document.getElementById('uName'),
pass1 = document.getElementById("pWord1");
//Using ajax made the function to check if the text box value is empty or not
//when that text box has focus.
if ($("#fName").is(':focus')){
if (fName.value.length <= 3){
msg.innerHTML = "First name is too short";
}else{
msg.innerHTML = "";
lName.disabled = false;
}
}
if ($("#lName").is(':focus')){
if (lName.value === fName.value){
msg.innerHTML = "Last and first name can't be the same";
pass1.disabled = true;
}else{
if (lName.value.length <= 3){
msg.innerHTML = "Last name is too short";
}else{
msg.innerHTML = "";
uName.disabled = false;
}
}
}
if ($("#uName").is(':focus')){
if (uName.value.length <= 3){
msg.innerHTML = "User name is too short";
pass1.disabled = true;
}else{
if(uName.value.length > 0){
checkUname();
}
}
}
function checkUname() {
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
if (xmlhttp.responseText === "1"){
msg.innerHTML="Username taken";
pass1.disabled = true;
}else{
msg.innerHTML = "";
pass1.disabled = false;
}
}
};
xmlhttp.open("POST","../Functions/matchUname.php?uName="+uName.value,true);
xmlhttp.send();
}
}
function checkLength() {
var pass1 = document.getElementById("pWord1"),
pass2 = document.getElementById("pWord2"),
passLength1 = pass1.value.length;
if(passLength1 <= 4){
document.getElementById("msg").innerHTML ="Password is less than 4 characters!";
}else{
document.getElementById("msg").innerHTML ="";
pass2.disabled = false;
}
}
function checkPass() {
var pass1 = document.getElementById("pWord1"),
pass2 = document.getElementById("pWord2"),
uTeam = document.getElementById("uTeam"),
matchColor = "#66cc66",
noMatchColor = "#ff6666";
if (pass1.value === pass2.value){
document.getElementById("msg").innerHTML ="Passwords match!";
pass1.style.backgroundColor = matchColor;
pass2.style.backgroundColor = matchColor;
uTeam.disabled = false;
}else{
document.getElementById("msg").innerHTML ="Passwords do not match!";
pass1.style.backgroundColor = noMatchColor;
pass2.style.backgroundColor = noMatchColor;
}
}
function enableRoles() {
var team = document.getElementById("uTeam").value,
teamId = document.getElementById("uTeamId").value,
tlCheck = document.getElementById("tl"),
role = document.getElementsByClassName("userRoles");
if (team !== ""){
//For loop to enable radio buttons
for (var i = 1; i < role.length; i++){
role[i].disabled = false;
//This part will take the team is from uTeamId text box
//send it to getTeam.php checks if that team has a leader if that team has a leader
//"set" value will be returned making the check box for team attribute team leader disabled.
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
// document.getElementById("msgID").innerHTML = xmlhttp.responseText;
tlCheck.disabled = xmlhttp.responseText === "set";
}
};
xmlhttp.open("POST","../Functions/getTeam.php?teamId="+teamId,true);
xmlhttp.send();
}
}
}
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
It's working with out any errors but I want to disable the Admin user type if the logged in user is not a admin. I can get this done by using pure PHP but it breaks the flow of the form.
In my HTML/PHP form I have used PHP to archive what I'm describing but it not really what want to do I want use JavaScript or jQuery or AJAX to archive this.
The PHP I use:
<div id="userRoles">
<label for="userRoles">User Role:</label><label for="uAttrib" style="margin-left: 250px;">User Attributes:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" class="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>"
<?php if ($_SESSION["uRole"] != "1" && $row["userRole"] == "Admin" ){?> disabled <?php } ?>><?php echo $row["userRole"]; }?>
<input type="checkbox" id="tl" name="tl" value="yes" style="margin-left: 120px;" disabled>Team Leader
</div>
Can some direct me down the right path or show me how to do this.
UPDATE:
After talking with professionals I learned that what I was trying to do is to shoot my self in the foot by my own gun. It's a bad idea to use client side languages to handle security options and WE CAN'T TRUST THE USER. My main issues was the flow of the form but security trumps the beauty so this will be split in to another one which the normal user want even see the admin option.
I would like to leave this question here and don't mind if it get closed so others can learn something from my mistake.
Just to nail this one down...
After a nice chat discussion, it appears that Jack (OP) has understood the importance not to manage user level security on client side.
The questions no longer needs more answer.
;)

Making JS Alert Look More Professional

Can someone help me make this alert look much nicer? Like Maybe split up Each text box on its own line? I can not figure out how to make this look a lot cleaner and not just all piled on one line.
To see alert hit Lien radio button and then hit next without filling textboxes
http://jsfiddle.net/t4Lgm0n2/9/
function validateForm(){
var QnoText = ['lien']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'lname';
var eD = "";
if (CkStatus && document.getElementById(ids).value == '') {
eD = eD+' lienholder name';
document.getElementById(ids).focus();
flag = false;
}
ids2 = QnoText[i]+'laddress';
if (CkStatus && document.getElementById(ids2).value == '') {
eD=eD+' lienholder address';
document.getElementById(ids2).focus();
flag = false;
}
ids3 = 'datepicker2';
if (CkStatus && document.getElementById(ids3).value == '') {
eD=eD+' lien date';
document.getElementById(ids3).focus();
flag = false;
}
if(eD!="") alert("Please enter "+eD);
}
return flag;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" required="yes" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 > .clearfix input:text").val("");
}
}
</script>
<div id="div1" style="display:none">
<div class="clearfix">
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" validateat="onSubmit" validate="maxlength" id="lienlname" size="54" maxlength="120" message="Please enter lienholder name." value="">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" validateat="onSubmit" validate="maxlength" id="lienladdress" size="54" maxlength="120" message="Please enter lienholder address." value="">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2" mask="99/99/9999" value="">
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<input type="submit" name="submit" value="Next" onclick="validateForm()">
You can use new line characters \n to make text more readable:
var eD = [];
if (CkStatus && document.getElementById(ids).value == '') {
eD.push('Please enter lienholder name');
document.getElementById(ids).focus();
flag = false;
}
// ...
if (eD.length) alert(eD.join('\n'));
As you can see I'm also pushing error messages into ed array, which makes it more convenient to concatenate resulting message using .join() method.
Demo: http://jsfiddle.net/t4Lgm0n2/11/

Reset My form after submission

After my form is submitted, I'd like to reset my form to display the original blank values. Here's the code:
PHP Form
<form action="index.php" method="post" id="contact_form" >
<div id="topic_error" class="error"><img src="images/error.png" /> What category should this be filed in?</div>
<div>
<select name="topic" id="topic">
<option value="">Please select a topic...</option>
<option value=" Computer Repair ">Computer Repair</option>
<option value=" Website Design ">Website Design</option>
<option value=" Say Hi ">Just Want to Say Hi</option>
</select>
</div>
<h4>NAME:</h4><div id="name_error" class="error"><img src="iamges/error.png" /> Please enter your name</div>
<div><input class="contact_name" type="text" name="name" id="name" placeholder="Enter Name" /></div>
<H4>EMAIL:</H4><div id="email_error" class="error"><img src="images/error.png" /> Please enter your email</div>
<div><input class="contact_email" type="text" name="email" id="email" placeholder="you#mail.com" /></div>
<h4>SUBJECT:</h4><div id="subject_error" class="error"><img src="images/error.png" /> Please enter a subject</div>
<div><input class="contact_subject" type="text" name="subject" id="subject" placeholder="How did you become so awesome?" /></div>
<h4>MESSAGE:</h4><div id="message_error" class="error"><img src="images/error.png" /> Please give us a few more details</div>
<div><textarea class="contact_message" name="message" id="message" placeholder="Give us some details"></textarea></div>
<div id="mail_success" class="success"><img src="images/success.png" /> Thank you. The mailman is on his way.</div>
<div id="mail_fail" class="error"><img src="images/error.png" /> Sorry, we don't know what happened. Please try again later.</div>
<div id="cf_submit_p">
<input class="submit" type="submit" id="send_message" value="">
</div>
</form>
The contact.js file
$(document).ready(function(){
$('#send_message').click(function(e){
e.preventDefault();
var error = false;
var topic = $('#topic').val();
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
if(topic.length == 0){
var error = true;
$('#topic_error').fadeIn(500);
} else {
$('#topic_error').fadeOut(500);
}
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
} else {
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
} else {
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
} else {
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
} else {
$('#message_error').fadeOut(500);
} if(error == false){
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
$.post("send_email.php", $("#contact_form").serialize(),function(result){
if(result == 'sent'){
$('#cf_submit_p').remove();
$('#mail_success').fadeIn(500);
} else {
$('#mail_fail').fadeIn(500);
$('#send_message').removeAttr('disabled').attr('value', 'Send Message');
}
});
}
});
});
I don't think the send_email.php file is needed, but I can put that up here if need be. I would assume (I know what happens when you assume) that this can be done with some sort of trigger in the javascript. I did try to add the line form.trigger('reset'); after the $('#mail_success').fadeIn(500); line but that did not work
It would be $("#contact_form").trigger("reset"), and $("#contact_form")[0].reset() should also work.
$('#contact_form').trigger('reset') should work.

Categories