Losing variables values between form and javascript - javascript

I am having a lot of trouble with form values, first I echoed out the MYSQL insert function to see what data was attempting to be put into the database and for one MYSQL insert function it was replacing most of my entered data into '' so first I thought it was my preg_replace function in the PHP part of my code but I removed this and the same thing was still happening, I am now not sure where it has gone wrong but I am guessing somewhere between the Javascript and the form. I really am lost on where to turn now. The INSERT function for the User table works perfectly fine it picks up all the entered data but with this Member table it is a different story
Javascript
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem === "email"){
rx = /[' "]/gi;
} else if(elem === "username"){
rx = /[^a-z0-9]/gi;
} else if(elem === "mobileNumber"){
rx = /[^0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u !== ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) === true) {
_("unamestatus").innerHTML = ajax.responseText;
}
};
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var m = _("mobileNumber").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var ci = _("city").value;
var pc = _("postcode").value;
var c = _("country").value;
var d = _("dateOfBirth").value;
var g = _("gender").value;
var ln = _("lastName").value;
var fn = _("firstName").value;
var status = _("status");
if(u === "" || e === "" || p1 === "" || p2 === "" || c === ""
|| g === "" || m === "" || ci === "" || pc === "" || d === "" ){
status.innerHTML = "Fill out required fields";
} else if(p1 !== p2){
status.innerHTML = "Your password fields do not match";
}else if(m.value !== 11 && isNaN(m)){
status.innerHTML = "Please enter valid mobile number";
}else if(d === "dd/mm/yyyy"){
status.innerHTML = "Please enter your date of birth";
} else {
//ajax to send form data to php
//hides sign button
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
//wait until php verifies data
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) === true) {
//if sign not succesful unhide button
if(ajax.responseText !== "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+"";
}
}
};
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ci"+ci+"&m"+m+"&pc"+pc+"&d"+d);
}
}
Form
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="email" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>First name:</div>
<input id="firstName" type="text" /><br />
<div>Last name:</div>
<input id="lastName" type="text" /><br />
<div>Mobile number*:</div>
<input id="mobileNumber" onfocus="emptyElement('status')" onkeyup="restrict('mobileNumber')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("country_list.php"); ?>
</select>
<div>City:</div>
<input id="city" onfocus="emptyElement('status')">
<div>Postcode:</div>
<input id="postcode" onfocus="emptyElement('status')">
<div>Relationship Status*:</div>
<select id="relationshipStatus" >
<option value=""></option>
<option value="Single">Single</option>
<option value="Taken">Taken</option>
</select>
<div>Date of Birth*:</div>
<input id="dateOfBirth" type="text" onfocus="emptyElement('status')">
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
INSERT functions
$sql = "INSERT INTO Member (`firstName`, `lastName`, `gender`, `emailAddress`,
`city`, `country`, `postCode`, `relationshipStatus`, `mobileNumber`, `dateOfBirth`)
VALUES('$fn', '$ln', '$g', '$e', '$ci', '$c', '$pc', '$rs', '$m', '$d')";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO User (`Userid`, `username`, `password`, `accountType`) VALUES ('$uid','$u','$p','$accountType')";
$query = mysqli_query($db_conx, $sql);

Related

Validate Form not working - form and validation

$(function(){
$("#submit").click(function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var phone = $("#phone").val();
var email = $("#email").val();
var ans = true;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if(first_name === ""){
window.alert("لا يمكنك ترك خانةالاسم فارغة");
$("#first_name").addClass("WrongInp");
ans = false;
}else{
$("#first_name").removeClass("WrongInp");
}
if(last_name === ""){
window.alert("لا يمكنك ترك خانةاسم العائلة فارغة");
$("#last_name").addClass("WrongInp");
ans = false;
}else{
$("#last_name").removeClass("WrongInp");
}
if(phone.value === ""){
window.alert("لا يمكنك ترك خانةالهاتف فارغة");
$("#phone").addClass("WrongInp");
ans = false;
}else{
$("#phone").removeClass("WrongInp");
}
if(phone.length < 9 || phone.length > 14){
window.alert("ادخل رقم هاتف صحيح");
$("#phone").addClass("WrongInp");
ans = false;
}else{
$("#phone").removeClass("WrongInp");
}
if (email === '') {
alert('الرجاء ادخال البريد الالكتروني');
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("البريد الالكتروني غير صحيح");
return false;
}
if(ans === true){
var url = 'Cant Reveal';
var form = new FormData();
form.append("first_name", $('#first_name').val());
form.append("last_name", $('#last_name').val());
form.append("phone", $('#phone').val());
form.append("email", $('#email').val());
form.append("status", "new");
var settings = {
"url": "cant Reveal",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": "Cant Reveal"
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
window.location.href = "www.google.com";
});
}
return false;
});
});
<form id="myForm">
<input name="first_name" id="first_name" class="input" type="text" placeholder="الاسم الكامل" required />
<input name="phone" id="phone" minlength="8" maxlength="15" class="input" type="text" placeholder="الجوال" required />
<input name="email" id="email" pattern="[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" class="input" type="text" placeholder="البريد الالكتروني" required />
<button type="text" class="submit">submit</button>
<input type="hidden" name="last_name" id="last_name" value="LN">
</form>
what is wrong with my code I change something in the javascript section and can't get it back working again!
i think i made changes in the javascript,
first i validate the form and then i submit it with ans
ans must be true
and if one of the fields empty or phone and email doesnt match my validation if goes to false and do not continue
any suggestions to make in javascript section
or maybe i can delete this section and write another better one ....
The click handler does not work because you bind it to the HTML element with the id submit - $("#submit").
In the provided HTML you're using a class submit, not the id.
<button type="text" class="submit">submit</button>
To make a handler work change this line:
$("#submit").click(function(){
to this one
$(".submit").click(function(){
Another option is to use id instead of class in the HTML
<button type="text" id="submit">submit</button>
any suggestions to make in javascript section or maybe i can delete this section and write another better one ....
If you are a beginner, it's completely ok to have it like this. If you want to make it a bit cleaner (since you're using jQuery), I'd suggest you take a look at the plugin like - jquery-validation
Give this a go. Your event handler wasn't attached to your button.
$(document).ready(function(){
$("#submit").click(function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var phone = $("#phone").val();
var email = $("#email").val();
var ans = true;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if(first_name === ""){
window.alert("لا يمكنك ترك خانةالاسم فارغة");
$("#first_name").addClass("WrongInp");
ans = false;
}else{
$("#first_name").removeClass("WrongInp");
}
if(last_name === ""){
window.alert("لا يمكنك ترك خانةاسم العائلة فارغة");
$("#last_name").addClass("WrongInp");
ans = false;
}else{
$("#last_name").removeClass("WrongInp");
}
if(phone.value === ""){
window.alert("لا يمكنك ترك خانةالهاتف فارغة");
$("#phone").addClass("WrongInp");
ans = false;
}else{
$("#phone").removeClass("WrongInp");
}
if(phone.length < 9 || phone.length > 14){
window.alert("ادخل رقم هاتف صحيح");
$("#phone").addClass("WrongInp");
ans = false;
}else{
$("#phone").removeClass("WrongInp");
}
if (email === '') {
alert('الرجاء ادخال البريد الالكتروني');
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("البريد الالكتروني غير صحيح");
return false;
}
if(ans === true){
var url = 'Cant Reveal';
var form = new FormData();
form.append("first_name", $('#first_name').val());
form.append("last_name", $('#last_name').val());
form.append("phone", $('#phone').val());
form.append("email", $('#email').val());
form.append("status", "new");
var settings = {
"url": "cant Reveal",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": "Cant Reveal"
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
window.location.href = "www.google.com";
});
}
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input name="first_name" id="first_name" class="input" type="text" placeholder="الاسم الكامل" required />
<input name="phone" id="phone" minlength="8" maxlength="15" class="input" type="text" placeholder="الجوال" required />
<input name="email" id="email" pattern="[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" class="input" type="text" placeholder="البريد الالكتروني" required />
<button type="text" class="submit">submit</button>
<input type="hidden" name="last_name" id="last_name" value="LN">
</form>

External js file not working with HTML file

Currently I am building a website which this page uses an external javascript file, one of the main function is that in the form if the user does not enter anything or enter the wrong value and clicks on the submit button, a error message will show up above each section, but unfortunately mine when I click on the submit button it will still submit and will not show any error, I suspect that the Javascript file is not linked properly but I did set the path correctly as you can see in the picture and the on the HTML page.
HTML File:
<meta charset="utf-8" />
<meta name="description" content="Demonstrates some basic HTML content elements and CSS" />
<meta name="keywords" content="html, css" />
<meta name="author" content="Jordan Siow" />
<link rel = "stylesheet" type = "text/css" href = "styles/style.css"/>
<script type="text/JavaScript" src="scripts/apply.js"></script>
<title>Apply </title>
<section class="front_title">
<p> Company XIT <img src="styles/images/logo.png" alt="logo" height="70" width="250"/>
</p>
</section>
<section class="topnav">
<table>
<tr>
<td >
Main
</td>
<td >
Jobs
</td>
<td id="current">
Apply
</td>
<td>
About
</td>
<td>
Enhancements
</td>
</tr>
</table>
</section>
<section id="style_apply">
<h2>Submit your Application!</h2>
<form method="post" id="apply_form" action="https://mercury.swin.edu.au/it000000/formtest.php">
<p><span id="job_id_error" class="error"></span></p>
<p><label for="jobid">Job Reference Number</label>
<input type="text" name="jobid" id="jobid" maxlength="5" pattern="[0-9]{5}" /></p>
<p><span id="firstname_error" class="error"></span></p>
<p><label for="firstname">First Name</label>
<input type ="text" name="First Name" id="firstname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<p><span id="lastname_error" class="error"></span></p>
<p><label for="lastname">Last Name</label>
<input type ="text" name="Last Name" id="lastname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<br/>
<p><span id="dob_error" class="error"></span></p>
<p><label for="dateofbirth">Date of Birth</label>
<input type="date" name="Date of Birth" id="dateofbirth" /></p>
<br/>
<br/>
<label>Gender</label>
<p><span id="gender_error" class="error"></span></p>
<fieldset id="gender">
<label for="male">Male</label>
<input type="radio" id="male" name="Gender" value="male" />
<label for="female">Female</label>
<input type="radio" id="female" name="Gender" value="female"/>
<label for="other">Others</label>
<input type="radio" id="other" name="Gender" value="other"/>
<label for="rathernotsay">Rather Not Say</label>
<input type="radio" id="rathernotsay" name="Gender" value="rathernotsay"/>
</fieldset>
<br/>
<div id="fieldset_label">
<label>Address Information</label>
</div>
<fieldset>
<p><span id="streetaddress_error" class="error"></span></p>
<p><label for="streetaddress">Street address</label>
<input type="text" name="Address" id="streetaddress" maxlength="40" "/></p>
<p><span id="suburb_error" class="error"></span></p>
<p><label for="suburb">Suburb/town</label>
<input type="text" name= "Suburb" id="suburb" maxlength="40" /></p>
<p><span id="state_error" class="error"></span></p>
<p><label for="state">State</label>
<select id="state" name="State">
<option value="">Please select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select></p>
<p><span id="postcodr_error" class="error"></span></p>
<p><label for="postcode">Postcode</label>
<input type="text" name= "Postcode" id="postcode" maxlength="4" pattern="\d{4}" placeholder="Postcode"/></p>
</fieldset>
<br/>
<p><span id="email_error" class="error"></span></p>
<p><label for="email">Email</label>
<input type="text" name="Email Address" id="email" /></p>
<p><span id="phonenumber_error" class="error"></span></p>
<p><label for="phonenumber">Phone Number</label>
<input type="text" name="Phone Number" id="phonenumber" maxlength="12" pattern="[0-9]{8-12}" ></p>
<label>Skill list</label>
<fieldset>
<p><span id="skill_error" class="error"></span></p>
<label for="skill1">Web development languages</label>
<input type="checkbox" id="skill1" name="Skill 1" value="skill"/>
<label for="skill2">Data Management abilities</label>
<input type="checkbox" id="skill2" name="Skill 2" value="skill"/>
<label for="skill3">Others</label>
<input type="checkbox" id="skill3" name="Other" value="skill"/>
<br/>
<br/>
<section>
<label for="comm" style="display:block">Other skillset</label>
<textarea class="comments" id="comm" name="Comments" rows="5" cols="50" placeholder="Other skillsets..."></textarea>
</section>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/>
<div class="align_center">
<p><span id="error_check" class="error"></span></p>
<input type="submit" value="Submit Application"/>
<input type="reset" value="Reset Application form"/>
</div>
</form>
</section>
<br/>
<br/>
<br/>
<br/>
<footer class = "footer_text">
<hr/>
<p>
<strong>©</strong>
<a class="footer_text" href="http://www.swinburne.edu.au/">
Swinburne Universty of Technology
</a>
</p>
<p>  
 
<strong>Done by:</strong> <a class="footer_text" href="mailto:103173691#student.swin.edu.au">
Jordan Siow</a>
</p>
</footer>
JS File:
/* To Validate the Form */
function validate(){
// Initialises the result variable
var result = true;
// Intialises the error tags
var job_id_error = document.getElementById("job_id_error");
job_id_error.innerHTML = "";
var firstname_error = document.getElementById("firstname_error");
firstname_error.innerHTML = "";
var lastname_error = document.getElementById("lastname_error");
lastname_error.innerHTML = "";
var dob_error = document.getElementById("dob_error");
dob_error.innerHTML = "";
var gender_error = document.getElementById("gender_error");
gender_error.innerHTML = "";
var streetaddress_error = document.getElementById("streetaddress_error");
streetaddress_error.innerHTML = "";
var suburb_error = document.getElementById("suburb_error");
suburb_error.innerHTML = "";
var state_error = document.getElementById("state_error");
state_error.innerHTML = "";
var postcode_error = document.getElementById("postcode_error");
postcode_error.innerHTML = "";
var email_error = document.getElementById("email_error");
email_error.innerHTML = "";
var phonenumber_error = document.getElementById("phonenumber_error");
phonenumber_error.innerHTML = "";
var skill_error = document.getElementById("skill_error");
skill_error.innerHTML = ""
// If there is an error in the input it will set the result to false and displays an error message
// To get the variables from the form and will chgeck the given rules
var jobid = document.getElementById("jobid").value;
if (jobid == ""){
job_id_error.innerHTML = "Job Reference Number must not be blank";
result = false;
}
var firstname = document.getElementById("firstname").value;
if (!firstname.match(/^[a-zA-Z]+$/) || firstname.value == ""){
firstname_error.innerHTML = "First name must only contain alphabetic characters";
alert("First name must only contain alphabetic characters")
result = false;
}
var lastname = document.getElementById("lastname").value;
if (!lastname.match(/^[a-zA-Z\-]+$/) || lastname.value == ""){
lastname_error.innerHTML = "Last name must only contain aphabetic characters";
result = false;
}
var dateofbirth = document.getElementById("dateofbirth").value;
if (!dateofbirth.match(/\d{2}\/\d{2}\/\d{4}/)){
dob_error.innerHTML = "Invalid Date of Birth";
result = false;
}
var age = calculate_age(dateofbirth);
if (!isFinite(age) || isNaN(age)) {
dob_error.innerHTML = "Your Date of Birth role is not Available.";
result = false;
}
else if (age < 21 || age > 70) {
dob_error.innerHTML =
"You must be between 21 and 70 years old to apply.";
result = false;
}
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var other = document.getElementById("other").checked;
var rathernotsay = document.getElementById("rathernotsay").checked;
if (!(male || female || other || rathernotsay)) {
gender_error.innerHTML = "Please select a gender.";
result = false;
}
var streetaddress = document.getElementById("streetaddress").value;
if (streetaddress == "") {
streetaddress_error.innerHTML = "You must enter a street address.";
result = false;
}
var suburb = document.getElementById("suburb").value;
if (suburb == "") {
suburb_error.innerHTML = "You must enter a suburb or town";
result = false;
}
var postcode = Number(document.getElementById("postcode").value);
if (postcode == "") {
postcode_error.innerHTML = "You must select a postcode";
result = false;
}
var state = document.getElementById("state").value
if (state == "") {
state_error.innerHTML = "You must select a state";
result = false;
} else {
var tempMsg = validate_postcode(state, postcode);
if (tempMsg != "") {
state_error.innerHTML = tempMsg;
result = false;
}
}
var email = document.getElementById("email").value;
if (email == "") {
email_error.innerHTML = "You must enter an email address";
result = false;
}
var phonenumber = document.getElementById("phonenumber").value;
if (phonenumber == "") {
phonenumber_error.innerHTML = "You must enter a phone number";
result = false;
}
if (result){
storeBooking(firstname, lastname, dateofbirth, male, female, other, rathernotsay, streetaddress, suburb, state, postcode, email, phonnumber)
}
if (!result) {
document.getElementById("error_check").innerHTML = "Please correct all of the errors given above.";
}
return result;
}
/**
* calcualte age from date of birth
*/
function calculate_age(dateofbirth) {
var today = new Date();
var DateOfBirth = new Date(dateofbirth);
// get the difference between the years
var age = today.getFullYear() - DateOfBirth.getFullYear();
// get the difference between the months
var month = today.getMonth() - DateOfBirth.getMonth();
// if the dateofbirth month and day is earlier in the year
if (month < 0 || (month === 0 && today.getDate() < DateOfBirth.getDate())) {
age--; // remove a year
}
return age;
}
function validate_postcode(state, postcode) {
var errMsg = "";
switch (state) {
case "vic":
if (!((postcode >= 3000 && postcode <= 3999) || (postcode >= 8000 && postcode <= 8999))) {
errMsg += "Post Code not in Victoria.";
}
break;
case "nsw":
if (!((postcode >= 1000 && postcode <= 2599) || (postcode >= 2619 && postcode <= 2899) || (postcode >= 2921 && postcode <= 2999))) {
errMsg += "Post Code not in New South Wales.";
}
break;
case "qld":
if (!((postcode >= 4000 && postcode <= 4999) || (postcode >= 9000 && postcode <= 9999))) {
errMsg += "Post Code not in Queensland.";
}
break;
case "nt":
if (!(postcode >= 800 && postcode <= 999)) {
errMsg += "Post Code not in Northern Territory.";
}
break;
case "wa":
if (!(postcode >= 6000 && postcode <= 6999)) {
errMsg += "Post Code not in Western Australia.";
}
break;
case "sa":
if (!(postcode >= 5000 && postcode <= 5999)) {
errMsg += "Post Code not in Southern Australia.";
}
break;
case "tas":
if (!(postcode >= 7000 && postcode <= 7999)) {
errMsg += "Post Code not in Tasmania.";
}
break;
case "act":
if (!((postcode >= 200 && postcode <= 299) || (postcode >= 2600 && postcode <= 2618) || (postcode >= 2900 && postcode <= 2920))) {
errMsg += "Post Code not in Australian Capital Territory.";
}
break;
default:
errMsg = "Post Code not Valid.";
}
return errMsg;
}
/**
* Prefill the form from exisitng session data
*/
function prefill_id() {
var jobId_input = document.getElementById("jobid");
if (localStorage.jobId != undefined) {
// hidden input to submit details
jobId_input.value = localStorage.jobId;
jobId_input.readOnly = true;
} else {
jobId_input.readOnly = false;
}
}
/**
* Prefill the form from exisitng session data
*/
function prefill_form() {
prefill_id();
if (sessionStorage.firstname != undefined) {
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("dateofbirth").value = sessionStorage.dateofbirth;
document.getElementById("streetaddress").value = sessionStorage.streetaddress;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("phonenumber").value = sessionStorage.phonenumber;
switch (sessionStorage.gender) {
case "male":
document.getElementById("male").checked = true;
break;
case "female":
document.getElementById("female").checked = true;
break;
case "other":
document.getElementById("other").checked = true;
break;
case "rathernotsay":
document.getElementById("rathernotsay").checked = true;
break;
}
var skills = sessionStorage.skills;
document.getElementById("skill1").checked = skills.includes("skill1");
document.getElementById("skill2").checked = skills.includes("skill2");
document.getElementById("skill3").checked = skills.includes("skill3");
}
}
/**
* Store Job ID for pre fill in application form
*/
function storeJobId1() {
localStorage.jobId = document.getElementById("job1_id").innerHTML;
}
function storeJobId2() {
localStorage.jobId = document.getElementById("job2_id").innerHTML;
}
/**
* Store values for session
*/
function storeBooking(skill1, skill2, skill3, comm, firstname,
lastname, dateofbirth, streetaddress, suburb, state, postcode, email, phonenumber, male, female, other) {
// store values in sessionStorage
var skill_string = "";
if (skill1) {
skill_string = "skill1";
}
if (skill2) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill2";
}
if (skill3) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill3";
}
sessionStorage.skills = skill_string;
sessionStorage.firstname = firstname;
sessionStorage.lastname = lastname;
sessionStorage.dateofbirth = dateofbirth;
sessionStorage.streetaddress = streetaddress;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = ;
sessionStorage.email = email;
sessionStorage.phonenumber = phonenumber;
sessionStorage.comm = comm;
if (male) {
sessionStorage.gender = "male";
} else if (female) {
sessionStorage.gender = "female";
} else if (other) {
sessionStorage.gender = "other";
} else if (rathernotsay) {
sessionStorage.gender = "rathernotsay";
}
}
/*
This function is called when the browser window loads
it will register functions that will respond to browser events
*/
function init() {
if (document.title == "Available Jobs") {
document.getElementById("job1_apply").onclick = storeJobId1;
document.getElementById("job2_apply").onclick = storeJobId2;
} else if (document.title == "Application Form") {
prefill_form();
// register the event listener to the form
document.getElementById("apply_form").onsubmit = validate;
document.getElementById("apply_form").onreset = function () {
localStorage.clear();
prefill_id();
;}
}
}
window.onload = init;
I think you should check out this article: preventDefault() Event Method
When clicked, you should prevent the default behavior.
<script type="text/JavaScript" src="scripts/apply.js"></script>
Add the above script tag just before closing of body tag, it it best practice.
put a console.log("js file linked"); inside js file to test whether its linked or not.
Feel free to ask if it didn't work...
In the comments you mentioned
my friend told me its got to do with the last line in the js file "window.onload = init();
Your friend is correct - not sure if this is the only relevant thing, but here you are first running the function init() and the return value of that function is being saved into window.onload. Check out this example code:
function init() {
console.log(document.readyState);
}
window.onload = init();
console.log("Window onload is", window.onload);
Here init is run immediately and the return value of init will be saved to window.onload. This prints
loading
apply.js:315 Window onload is null
Instead, you should add a reference to the init function, so that the value of window.onload is your init function itself, not the return value; so the correction would be
function init() {
console.log(document.readyState);
}
window.onload = init;
console.log("Window onload is", window.onload);
// this one prints out
// Window onload is ƒ init() {console.log(document.readyState);}
// apply.js:311 complete
The "document.readyState" is used to check if the document has been loaded and parsed.

JavaScript: why did my form validation that runs onsubmit stop working when data transfer between pages is used?

my form validation codes work just fine when I'm not using .getitem and setitem to pass data from other pages to my enquiry page. I kinda know what the problem but my knowledge is so shallow that I can't comprehend and also don't know how to fix it. Anyone knows what to do bout this?
This is the 1st HTML file for product page (Relevant codes):
<button class="enqbutton margin-l50 margin-t50-b50 font-josefin" onclick="storeitem('Enclosed Space Sanitisation: Home')">Enquire</button>
this is the enquiry page:
<!-- enquiry form -->
<form id="detail" method="post" class="font-josefin" action="mailto:101231212#students.swinburne.edu.my" novalidate="novalidate" onsubmit="return validateForm()">
<fieldset>
<legend>Personal Details</legend>
<label class= 'margin-l50' for="fname">Name:</label><br/>
<input class= 'margin-l50' type="text" id="fname" name="fname" placeholder="Your name" size="50" maxlength="30" required="required"/>*<br/>
<label class= 'margin-l50' for="fmail">Email:</label><br/>
<input class= 'margin-l50' type="email" id="fmail" name="fmail" placeholder="Your email" size="50" maxlength="30" required="required"/>*<br/>
<label class= 'margin-l50' for="fhp">Personal Phone Number:</label><br/>
<input class= 'margin-l50' type="tel" id="fhp" name="fhp" placeholder="###-#######" size="50" required="required"/>*
</fieldset>
<fieldset>
<legend>Address</legend>
<label class= 'margin-l50' for="stname">Street Name:</label><br/>
<input class= 'margin-l50' type="text" id="stname" name="stname" placeholder="Street" size="50" maxlength="40" required="required"/>*<br/>
<label class= 'margin-l50' for="city">City/Town:</label><br/>
<input class= 'margin-l50' type="text" id="city" name="city" placeholder="City/Town" size="50" maxlength="20" required="required"/>*<br/>
<label class= 'margin-l50'>State:</label><br/>
<select class= 'margin-l50' name="state" id="statedrop">
<optgroup label="States">
<script>statelist()</script>
</optgroup>
</select>*<br/><br/>
<label class= 'margin-l50' for="fhp">Postcode:</label><br/>
<input class= 'margin-l50' type="text" id="postcode" name="postcode" placeholder="#####" size="50" required="required"/>*
</fieldset>
<fieldset>
<legend>Enquiries</legend>
<label class= 'margin-l50' for="subject" id="subjectLabel">Subject Enquiry On:</label><br/>
<input class= 'margin-l50' type="text" name="subject" id="subject" size="40" /><br/>
<label class= 'margin-l50'>Your queries:</label><br/>
<label class= 'margin-l50'>Service Categories:</label><br/>
<select class= 'margin-l50' name="query" id="servicedrop" onchange="change()">
<optgroup label="Services">
<script>serviceList()</script>
</optgroup>
</select>*<br/><br/>
<label class= 'margin-l50'>Description of your queries</label><br/>
<textarea class= 'margin-l50' id="description" name="description" rows="5" cols="50" placeholder="Enter your queries"></textarea>
</fieldset>
<fieldset>
<legend>Making Appointment</legend>
<label class= 'margin-l50' for="date">Date:</label>
<input class= 'margin-l50' type="date" id="date" name="date"/><br/>
<label class= 'margin-l50' for="time">Time:</label>
<input class= 'margin-l50' type="time" id="time" name="time"/><br/><br/>
<p class= 'margin-l50'>Our team will contact you within 1 business day upon booking to confirm the following booking.</p><br/>
</fieldset>
<div class="button_container">
<button type="submit" class="enqbutton font-josefin" value="Submit">Submit</button>
<button type="reset" class="enqbutton font-josefin" value="Reset">Reset</button>
</div>
</form>
This is the javascript file
var gErrorMsg = "";
function init() {
displayitem();
}
function validateForm(){
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var hpOk = chkHp();
var stOk = chkSt();
var cityOk = chkCt();
var stateOk = chkState();
var postOk = chkPost();
var subOk = chkSubject();
var selectOk = chkSelect();
if (nameOK && emailOK && hpOk && stOk && cityOk && stateOk && postOk && selectOk){
isAllOK = true;
}
else{
alert(gErrorMsg);
gErrorMsg = "";
isAllOK = false;
}
return isAllOK;
}
function chkName() {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/
var nameOk = true;
if ((name.length == 0)){
gErrorMsg = gErrorMsg + "Please enter your name\n"
nameOk = false;
}
else if ((name.length > 25)){
gErrorMsg = gErrorMsg + "Input name must be within 25 characters.\n"
nameOk = false;
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
function chkEmail() {
var email = document.getElementById("fmail");
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email.value)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkHp(){
var hp = document.getElementById("fhp").value;
var result = true;
var pattern = /^(\+?6?01)[0|1|2|3|4|6|7|8|9]\-*[0-9]{7,8}$/;
if (pattern.test(hp)){
result = true;
}
else{
result = false;
gErrorMsg = gErrorMsg + "Enter a valid Malaysian phone numbers (11 numerical digits allowed for numbers with '011' prefix) \n"
}
return result;
}
function chkSt() {
var street = document.getElementById("stname").value;
var pattern = /^[a-zA-Z ]+$/
var stOk = true;
if ((street.length == 0)){
gErrorMsg = gErrorMsg + "You must enter the name of the street of your living place\n"
stOk = false;
}
else if ((street.length > 20)){
gErrorMsg = gErrorMsg + "Input street name must be within 20 characters\n"
stOk = false;
}
else{
if (!pattern.test(street)){
gErrorMsg = gErrorMsg + "Street name must only contain alpha characters\n"
stOk = false;
}
}
return stOk;
}
function chkCt() {
var city = document.getElementById("city").value;
var pattern = /^[a-zA-Z ]+$/
var cityOk = true;
if ((city.length == 0)){
gErrorMsg = gErrorMsg + "You must enter the city of your living place\n"
cityOk = false;
}
else if ((city.length > 15)){
gErrorMsg = gErrorMsg + "Input city name must be within 15 characters\n"
cityOk = false;
}
else{
if (!pattern.test(city)){
gErrorMsg = gErrorMsg + "City name must only contain alpha characters\n"
cityOk = false;
}
}
return cityOk;
}
function chkState(){
var selected = false;
var state = document.getElementById("statedrop").value;
if (state!="------"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your state\n"
}
return selected;
}
function chkPost (){
var post = document.getElementById("postcode").value;
var result = true;
var pattern = /^[0-9]{5}$/;
if (pattern.test(post)){
result = true;
}
else{
result = false;
gErrorMsg = gErrorMsg + "Enter a valid Malaysian postcode with only 5 numerical digits\n"
}
return result;
}
function chkSubject() {
var sub = document.getElementById("subject").value;
var pattern = /^[a-zA-Z ]+$/
var subOk = true;
if ((sub.length == 0)){
gErrorMsg = gErrorMsg + "Subject is empty, must select category and service to enquiry on\n"
nameOk = false;
}
return nameOk;
}
function chkSelect(){
var selected = false;
var ser = document.getElementById("servicedrop").value;
if (ser!="Select a category and service"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select a category and service for your enquiry\n"
}
return selected;
}
// Array
function serviceList() {
var select = document.getElementById("servicedrop");
var options = [
"Select a category and service",
"Enclosed Space Sanitisation: Home",
"Enclosed Space Sanitisation: Office",
"Enclosed Space Sanitisation: Inventory",
"Enclosed Space Sanitisation: Sport Facilities",
"Event Hygiene Management: Funeral",
"Event Hygiene Management: Sports Event",
"Event Hygiene Management: Gatherings",
"Event Hygiene Management: Exhibitions",
"Wide Area Sanitisation: Hosuing Area",
"Wide Area Sanitisation: Shopping Complex",
"Wide Area Sanitisation: School Area",
"Wide Area Sanitisation: Food Court",
"Object Disinfection: Vehicle",
"Object Disinfection: Luggage",
"Object Disinfection: Walkthorugh Sanitisation",
"Object Disinfection: Professional Gears"
];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function statelist() {
var select = document.getElementById("statedrop");
var options = ["------", "Johor", "Kedah", "Kelantan", "Kuala Lumpur", "Labuan", "Malacca", "Negeri Sembilan", "Pahang", "Perak", "Perlis", "Penang", "Sabah", "Sarawak", "Selangor", "Terengganu"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function makeAnchor() {
var div = document.createElement('div');
var options = ['ENCLOSED SPACE SANITISATION','EVENT HYGIENE MANAGEMENT', 'WIDE AREA SANITISATION', 'OBJECT DISINFECTION'];
for(var i = 0; i < options.length; i++) {
// Create the list item:
var a = document.createElement('a');
var opt = options[i]
a.href = "./service" + (i + 1) + ".html"
a.appendChild(document.createTextNode(opt));
div.appendChild(a);
}
return div;
}
function makeAnchor2() {
var div = document.createElement('div');
var options = ['ENHANCEMENT 1', 'ENHANCEMENT 2'];
for(var i = 0; i < options.length; i++) {
// Create the list item:
var a = document.createElement('a');
var opt = options[i]
a.href = "./enhancements" + (i + 1) + ".html"
a.appendChild(document.createTextNode(opt));
div.appendChild(a);
}
return div;
}
window.addEventListener("load", function()
{document.getElementById('dropsc').appendChild(makeAnchor())});
window.addEventListener("load", function()
{document.getElementById('dropsc2').appendChild(makeAnchor2())});
// transfer within pages
function change() {
var service = document.getElementById("servicedrop").value;
if (service == "Select a category and service"){
document.getElementById("subject").value = "";
}
else{
sessionStorage.service = service;
document.getElementById("subject").value = sessionStorage.service;
}
sessionStorage.clear();
}
// Transfer between pages
function storeitem(item_id) {
sessionStorage.setItem("item_id", item_id);
window.location.href = "./enquiry.html";
}
function displayitem() {
var item_id = sessionStorage.getItem("item_id");
document.getElementById("subject").value = item_id;
if (item_id == "Enclosed Space Sanitisation: Home"){
document.getElementById("servicedrop").selectedIndex = "1";
};
sessionStorage.clear();
window.onload = validateForm;
}

validating using onblur and onsubmit

I would like to know how to validate a form when I use the onblur handler and the onsubmit handler at the same time. I've tried to do it and it goes straight to the submit page without displaying an error message.
Because I also have radio buttons and checkboxes, how do I validate these if the user didn't click the radio button and exclude the checkbox from validation.
Thank You
function IsNotBlank(tf, tfHelp) {
var value = tf.value;
if (value == " ") {
tf.className = "invalid ";
tfHelp.innerHTML = "This field can 't be blank.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckLetters(tf, tfHelp) {
//check empty field from previous function.
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
//assign field value
var value = tf.value;
//check if there is numbers.
var regex = new RegExp(/^[A-Za-z]{5,18}$/);
var testResult = regex.test(value);
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Use letters only and lengths must be between 5 and 18 characters.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPhNumber(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate phone number.
var regex = /^\d{8,10}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid phone number.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckEmail(tf, tfHelp) {
//check empty field
NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
var value = tf.value;
//validate email address
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid email address.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPostCode(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate postcode.
var regex = /^\d{4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a 4 digit post code.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return false;
}
}
function ValidateForm(form) {
var formCheck = true;
for (var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
//alert(form.elements[i]);
if (e.onblur) {
// alert(e.onblur());
formCheck = e.onblur() && formCheck;
}
}
return formCheck;
}
function ResetForm(form) {
//select input elements and change color back to default
var arrayInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrayInputs.length; i++) {
arrayInputs[i].className = "valid";
}
//clear text on span elements
var arraySpans = document.getElementsByTagName('span ');
for (var i = 0; i < arraySpans.length; i++) {
arraySpans[i].innerHTML = "";
}
}
<form action="submit.html" onreset="ResetForm()" onsubmit="ValidateForm(this);">
<div>
<label for="fname" class="label">First Name:</label>
<input class="valid" type="text" id="txtFname" onblur="return CheckLetters(this, txtFnameHelp);" />
<span id="txtFnameHelp"></span>
</div>
<div class="one">
<label for="lname" class="label">Last Name:</label>
<input class="valid" name="lname" id="txtLname" type="text" onblur="return CheckLetters(this, txtLnameHelp);" />
<span id="txtLnameHelp"></span>
</div>
<div class="one">
<label class="label" for="phone">Phone Number:</label>
<input class="one" id="txtPhone" type="text" onblur="CheckPhNumber(this, txtPhoneHelp);"><br>
<span id="txtPhoneHelp"></span>
</div>
<div class="one">
<label for="email" class="label">Email Address:</label>
<input class="valid" id="txtEmail" type="text" onblur="CheckEmail(this, txtEmailHelp)">
<span id="txtEmailHelp"></span><br>
</div>
<div class="one">
<label class="label">Post Code:</label>
<input id="txtPostcode" type="text" onblur="CheckPostCode(this, txtPostCodeHelp);"> <br>
<span id="txtPostCodeHelp"></span>
</div>
<br>
<div>
<label>Prefered Contact Method</label><br>
</div>
<div class="one">
</--<input type="radio" name="contact" value="email">Email
</-- <input type="radio" name="contact" value="phone">Phone
</div>
<br>
<div class="one">
<label>Your Message:</label><br />
<textarea id="txtMessage" rows="8" cols="40" onblur="IsNotBlank(this, txtMessageHelp)">Your Message</textarea>
<span id="txtMessageHelp"></span>
<br><br>
</div>
</--<input class="one" type="checkbox" name="newsletter" value="subscribe">I would like to subscribe to the newsletter <br>
<div>
<input class="one" type="submit" value="Send">
<input class="one " type="Reset " value="Clear">
<br><br>
</div>
</form>
Note that these type of JavaScript code can only be debugged using Microsoft Visual Studio for some reason and would not work on using legacy text editors.
You can use below concept to perform the both action and use window.addEventListener('DOMContentLoaded'function(e) {}) to check the validation
var error_user_name = false;
function checkpw(ele, e){
var user_name = document.forms["joinform"]["user_name"].value;
if (user_name == null || user_name == "") {
text = "UserName : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_name = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_name = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_name == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) { document.getElementById('user_name').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="text" name="user_name" id="user_name" placeholder="User_Name"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

Dynamic form insert database

My whole signup page code is here.
Link
I'm trying to add this dynamic fields to the signup page code.
<script>
var i = 1;
function addKid(){
if (i <= 6){
i++;
var div = document.createElement('div');
div.style.width = "44%";
div.style.height = "26px";
div.style.color = "white";
div.setAttribute('class', 'myclass');
div.innerHTML = 'Child : <input type="text" name="child_'+i+'" > Ages : <input type="text" name="ages_'+i+'"><input type="button" id="add_kid()" onClick="addKid()" value="+" /><input type="button" value="-" onclick="removeKid(this)">';
document.getElementById('kids').appendChild(div);
}
}
function removeKid(div) {
document.getElementById('kids').removeChild( div.parentNode );
i--; }
<div id="kids">
Child : <input id="child_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="50">
Ages : <input id="ages_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="10"><input type="button" id="add_kid()" onClick="addKid()" value="+" />
</div>
I can get the "child_1 / chi" and "ages_1 / ags" insert into my database. no problem.
When I try to create a extra dynamic field in my signup, "child_2 and ages_2".....
then I can't get that info from "child_2 and ages_2" insert into my database.
Can some one tell me what I'm doing wrong since I can't get that info into my database.? Am I suppose to call "child_2 / chi2" and "ages_2 / ags2" for something els before it will work.?
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$chi = preg_replace('#[^a-z.,-/ ]#i', '', $_POST['chi']);
$ags = preg_replace('#[^0-9.]#i', '', $_POST['ags']);
$chi2 = preg_replace('#[^a-z.,-/ ]#i', '', $_POST['chi2']);
$ags2 = preg_replace('#[^0-9.]#i', '', $_POST['ags2']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $chi == "" || $ags == "" || $chi2 == "" || $ags2 == "" || $c == ""){
..
$sql = "INSERT INTO users (username, email, password, gender, child_1, ages_1, child_2, ages_2, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$chi','$ags','$chi2','$ags2','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
..
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
} else if(elem == "child_1"){
rx = /[^a-z.,-/ ]/gi;
} else if(elem == "ages_1"){
rx = /[^0-9.]/gi;
} else if(elem == "child_2"){
rx = /[^a-z.,-/ ]/gi;
} else if(elem == "ages_2"){
rx = /[^0-9.]/gi;
}
tf.value = tf.value.replace(rx, "");
}
..
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var chi = _("child_1").value;
var ags = _("ages_1").value;
var chi2 = _("child_2").value;
var ags2 = _("ages_2").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || chi == "" || ags == "" || chi2 == "" || ags2 == "" || g == ""){
..
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&chi="+chi+"&ags="+ags+"&chi2="+chi2+"&ags2="+ags2+"&g="+g);
}
..
kindly save your child and age in array and pass it in ajax. so that you can loop the child and age as given below and insert it into table.
For password and conform password use js. and validate it in front end itself. save password alone in table that's enough.
try to understand this code and do alterations as required. but i sloved your dynamic child and age problem. run this code
page1.php
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</script></script>
<script type="text/javascript">
$(document).ready(function(){
$("#input_form").submit(function(){
var querystring = $(this).serialize();
$.ajax({
url: 'save_child.php',
type: "POST",
data: querystring,
success: function(data) {
alert("jhkl");
}
});
//$('#result').html(querystring);
return false;
});
});
</script>
<title>Serialize</title>
</head>
<body>
<form id="input_form">
first name: <input type="text" name="username" id="first name"/><br />
password: <input type="text" name="password" id="last name"/><br />
email: <input type="text" name="email" id="email"/><br />
<div id="kids">
Child : <input id="child_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="50" name="child[]">
Ages : <input id="ages_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="10" name="ages[]"><input type="button" id="add_kid()" onClick="addKid()" value="+" />
</div>
<input type="submit" value="send" name="submit" />
</form>
<p id="result"></p>
</body>
</html><script>
var i = 1;
function addKid(){
if (i <= 5){
i++;
var div = document.createElement('div');
div.style.width = "44%";
div.style.height = "26px";
div.style.color = "white";
div.setAttribute('class', 'myclass');
div.innerHTML = 'Child : <input type="text" name="child[]" > Ages : <input type="text" name="ages[]"><input type="button" id="add_kid()" onClick="addKid()" value="+" /><input type="button" value="-" onclick="removeKid(this)">';
document.getElementById('kids').appendChild(div);
}
}
function removeKid(div) {
document.getElementById('kids').removeChild( div.parentNode );
i--; }
</script>
save_child.php
<?php
$child=$_REQUEST['child'];// child array
$ages=$_REQUEST['ages'];
$InputArray = array();
$conn=mysqli_connect("localhost","root","","tes");// data base connection
$InputArray['username']=$_REQUEST['username'];// get datas and store in a array named InputArray
$InputArray['password']=$_REQUEST['password'];
$InputArray['email']=$_REQUEST['email'];
$i=1;
foreach($child as $val){
$b=$i-1;
$InputArray['child_'.$i]=$val;
$InputArray['age_'.$i]=$ages[$b];
$i++;
}
$sql="CREATE TABLE IF NOT EXISTS `userss` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`email` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
`country` varchar(20) NOT NULL,
`child_1` varchar(20) NOT NULL,
`age_1` varchar(20) NOT NULL,
`child_2` varchar(20) NOT NULL,
`age_2` varchar(20) NOT NULL,
`child_3` varchar(20) NOT NULL,
`age_3` varchar(20) NOT NULL,
`child_4` varchar(20) NOT NULL,
`age_4` varchar(20) NOT NULL,
`child_5` varchar(20) NOT NULL,
`age_5` varchar(20) NOT NULL,
`ip` varchar(60) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ";
mysqli_query($conn,$sql);
if (count($InputArray) > 0) {
while (list($key, $val) = each($InputArray)) {
if(!empty($val)){
$fields.= $key . ',';
$valset.= "'". $val ."',";
}
}
}
$fields = trim($fields, ',');
$valset = trim($valset, ',');
$sql = "INSERT INTO userss ($fields) VALUES ($valset)";
mysqli_query($conn,$sql);
?>
Another one thing I have noted in your code.
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
you have written two query for this. make it single as given
$sql = "SELECT id FROM users WHERE email='$e' and username='$u' LIMIT 1";

Categories