Im making a form validation and im creating a dom dynamically but when I press the submit button to create the error it is calling the element multiple times instead of once. So how can I make it call it once? Im a little lost on this one.
Javascript:
function validateForm(){
var xfields=document.forms["form1"]["amt"].value;
if (xfields==null || xfields==""){
var errortag = document.createElement('label');
var realinput = document.getElementById('amt');
var errortagname = 'error';
errortag.setAttribute('class',errortagname);
errortag.innerHTML = 'Amount of loan needed';
var adddiv = document.getElementById('amtloan').insertBefore(errortag, realinput.nextSibling);
if(adddiv === true){
document.getElementById('amtloan').insertBefore(errortag, realinput.nextSibling);
return false;
}else{
xfields.remove('errortag');
}
}
return true;
}
HTML
<div id="st-widget" style=" width: 393px; padding-bottom: 0;">
<form class="ui-form ui-widget-form" id="short_form" method="get" name="form1" target="_blank" onsubmit="return validateForm()">
<input type="hidden" > <input id="scl" name="scl" type="hidden" value="">
<input name="optInQ" type="hidden" value="t">
<input name="inplst" type="hidden" value="BSGAEOZ">
<div class="grad-date" style="clear:left; #width:138px;">
<label for="gradDate">When will you graduate?</label>
<select id="gradDate" name="gradDate" style="width:46px !important;" tabindex="10" title="Month">
<option selected="selected" value="">Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<select id="grad-month" name="gradDate" style="width:46px !important;" tabindex="15" title="Year">
<option selected="selected" value="">Year</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
</select>
</div>
<div id="amtloan" class="amount">
<label for="amt">Amount of loan needed?</label>
<input class="amt-input required" id="amt" name="amt" style="width:137px;" tabindex="20" title="Amount of loan needed" type="text" value="">
</div>
<div class="ui-form-action" style="margin-top:18px;">
<button class="ui-btn button" id="" name="go" tabindex="35" title="GO" type="submit" value="Submit">
<span class="ui-btn-ctn medium">Continue </span>
</button>
</div>
</form></div></div>
This line
var adddiv = document.getElementById('amtloan').insertBefore(errortag, realinput.nextSibling);
causes the errortag to be inserted every time you call the validator function. Try
//...
var adddiv = document.getElementsByClassName(errortagname).length == 0;
if(adddiv === true){
document.getElementById('amtloan').insertBefore(errortag, realinput.nextSibling);
}
return false;
}
Not sure what the else clause is supposed to do though.
There is a lot of potential for improvement, but I think Stackoverflow is not the right place to discuss the code in great detail.
Related
I am trying to set parameters to onClick event inside a html button using javascript.
This is how html button looks like:
<button type="button" id="upload-button" onclick="uploadFileIGCSE('param1', 'param2', 'param3')" class="btn btn-success" aria-expanded="false">Upload</button>
param1 = should be the value from a html select element with id='year' and name='year'
param2 = should be the value from a html select element with id='grade' and name='grade'
param3 = should be the value from a html select element with id='subject' and name='subject'
These are the html select options
<div class="col-md-3">
<select id="year" name="year" class="form-control">
<option value="select" disabled="disabled">- Select Year -</option>
<option value="1">2001</option>
<option value="2">2002</option>
<option value="3">2003</option>
</select>
</div>
<div class="col-md-3">
<select id="grade" name="grade" class="form-control">
<option value="select" disabled="disabled">- Select Grade -</option>
<option value="1">Grade 5</option>
<option value="2">Grade 6</option>
<option value="3">Grade 7</option>
</select>
</div>
<div class="col-md-3">
<select id="subject" name="subject" class="form-control">
<option value="select" disabled="disabled">- Select Subject -</option>
<option value="1">Edexcel</option>
<option value="2">National</option>
<option value="3">Other</option>
</select>
</div>
I have no clue how to set values to param1, param2, param3
This is what I tried but it feels wrong.
$('#upload-button').val = $('#year').val;
Can someone please help me?
I need to set values for the parameters (param1, param2, param3) in the function uploadFileIGCSE('param1', 'param2', 'param3') using javascript or jquery
Thank you
I can understand your needs. if you really wanted to do this only with HTML element, here is the way.
<button type="button" id="upload-button"
onclick="uploadFileIGCSE(
document.querySelector('#year').value,
document.querySelector('#grade').value,
document.querySelector('#subject').value)"
class="btn btn-success" aria-expanded="false">Upload</button>
Here is the working example
function uploadFileIGCSE(val1, val2, val3){
document.querySelector('#log').innerHTML = `${val1}, ${val2}, ${val3}`
}
<div class="col-md-3">
<select id="year" name="year" class="form-control">
<option value="select" disabled="disabled">- Select Year -</option>
<option value="1">2001</option>
<option value="2">2002</option>
<option value="3">2003</option>
</select>
</div>
<div class="col-md-3">
<select id="grade" name="grade" class="form-control">
<option value="select" disabled="disabled">- Select Grade -</option>
<option value="1">Grade 5</option>
<option value="2">Grade 6</option>
<option value="3">Grade 7</option>
</select>
</div>
<div class="col-md-3">
<select id="subject" name="subject" class="form-control">
<option value="select" disabled="disabled">- Select Subject -</option>
<option value="1">Edexcel</option>
<option value="2">National</option>
<option value="3">Other</option>
</select>
</div>
<button type="button" id="upload-button"
onclick="uploadFileIGCSE(
document.querySelector('#year').value,
document.querySelector('#grade').value,
document.querySelector('#subject').value)"
class="btn btn-success" aria-expanded="false">Upload</button>
<p>log value : (<span id="log"></span>)</p>
You really shouldn't be using inline event listeners like onclick (for maintainability, security and separation of concerns reasons).
Instead, add the listener using the DOM API's HTMLElement.prototype.addEventListener():
document.getElementById('upload-button').addEventListener('click', function() {
uploadFileIGCSE(year.value, grade.value, subject.value);
})
function uploadFileIGCSE(x,y,z) {
console.log(x,y,z);
}
document.getElementById('upload-button').addEventListener('click', function() {
uploadFileIGCSE(year.value, grade.value, subject.value);
})
<div class="col-md-3">
<select id="year" name="year" class="form-control">
<option value="select" disabled="disabled">- Select Year -</option>
<option value="1">2001</option>
<option value="2">2002</option>
<option value="3">2003</option>
</select>
</div>
<div class="col-md-3">
<select id="grade" name="grade" class="form-control">
<option value="select" disabled="disabled">- Select Grade -</option>
<option value="1">Grade 5</option>
<option value="2">Grade 6</option>
<option value="3">Grade 7</option>
</select>
</div>
<div class="col-md-3">
<select id="subject" name="subject" class="form-control">
<option value="select" disabled="disabled">- Select Subject -</option>
<option value="1">Edexcel</option>
<option value="2">National</option>
<option value="3">Other</option>
</select>
</div>
<button type="button" id="upload-button">Upload</button>
try this
<button type="button" id="upload-button" onclick="getOption()" class="btn btn-success"
aria-expanded="false">Upload</button>
function getOption() {
var year = document.getElementById("year");
var year_option = year.options[year.selectedIndex].value;
var grade = document.getElementById("grade");
var grade_option = grade.options[grade.selectedIndex].value;
var subject = document.getElementById("subject");
var subject_option = subject.options[subject.selectedIndex].value;
uploadFileIGCSE(year_option, grade_option, subject_option)
}
$('#upload-button').click(function(e) {
var year = $('#year').val();
var grade = $('#grade').val();
var subject = $('#subject').val();
uploadFileIGCSE(year, grade, subject);
})
You could try something like this.
The click event can simply run an anonymous function. Its only input will be the default event object supplied by the DOM engine. That function can then gather the values from the various elements you're interested in, and make a further call to the uploadFileIGCSE function, passing those values as parameters.
Here's a demo. Note that I've used an unobtrusive event handler using addEventListener() in the JS code, rather than "onclick" within the HTML. This is generally considered to be better practice, as it makes the code easier to read, maintain and debug, and helps to separate the functionality from the presentation.
N.B. you could use jQuery for any/all of this, but equally it's not really necessary, it doesn't really add much value in this situation.
var button = document.getElementById("upload-button");
button.addEventListener("click", function(event) {
var year = document.getElementById("year").value;
var grade = document.getElementById("grade").value;
var subject = document.getElementById("subject").value;
uploadFileIGCSE(year, grade, subject);
});
function uploadFileIGCSE(year, grade, subject) {
console.log(year, grade, subject);
}
<button type="button" id="upload-button" onclick="uploadFileIGCSE('param1', 'param2', 'param3')" class="btn btn-success" aria-expanded="false">Upload</button>
<div class="col-md-3">
<select id="year" name="year" class="form-control">
<option value="select" disabled="disabled">- Select Year -</option>
<option value="1">2001</option>
<option value="2">2002</option>
<option value="3">2003</option>
</select>
</div>
<div class="col-md-3">
<select id="grade" name="grade" class="form-control">
<option value="select" disabled="disabled">- Select Grade -</option>
<option value="1">Grade 5</option>
<option value="2">Grade 6</option>
<option value="3">Grade 7</option>
</select>
</div>
<div class="col-md-3">
<select id="subject" name="subject" class="form-control">
<option value="select" disabled="disabled">- Select Subject -</option>
<option value="1">Edexcel</option>
<option value="2">National</option>
<option value="3">Other</option>
</select>
</div>
I created a fairly simple application to query a third-party API.
My issue is that I expected to get the entire URI http://uinames.com/api/?region=japan& in the console (see console.log(…)) but I only get the ?region=japan& part.
I am not getting any error, does anyone can spot what is wrong with my implementation ?
My code
// Execute the function to query the API
function loadNames(e) {
e.preventDefault();
// Read the values from the form and create the variables
const origin = document.getElementById('#country').value;
const gender = document.getElementById('gender').value;
const amount = document.getElementById('quantity').value;
// Build the URL
let url = 'http://uinames.com/api/?';
// Read the origin and append to url
if (origin !== '') {
url += `region=${origin}&`;
}
console.log(url);
}
document.querySelector('#generate-names').addEventListener('submit', loadNames);
<body>
<div class="container">
<div id="content" class="content">
<h1>Generate Names</h1>
<form id="generate-names" action="#">
<div class="row">
<div class="six-columns">
<label for="country">Filter By Country:</label>
<select class="u-full-width" name="country">
<option value="">-- Select --</option>
<option value="argentina">Argentina</option>
<option value="brasil">Brasil</option>
<option value="colombia">Colombia</option>
<option value="costa rica">Costa Rica</option>
<option value="france">France</option>
<option value="italy">Italy</option>
<option value="mexico">Mexico</option>
<option value="portugal">Portugal</option>
<option value="united states">United States</option>
<option value="india">India</option>
<option value="japan">Japan</option>
</select>
<label for="gender">Gender:</label>
<select class="u-full-width" id="gender">
<option value="">-- Select --</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label>Number of names to generate</label>
<input type="number" id="quantity" class="u-full-width" min="5" max="15" value="5">
<input class="button-primary u-full-width" type="submit" value="Generate">
</div>
<div class="six-columns">
<div id="result"></div>
</div>
</div>
</form>
</div>
</div>
</body>
It works fine.
I fixed a few errors though.
const origin = document.getElementById('#country').value
Should be (without the #)
const origin = document.getElementById('country').value
No id had been asigned to the select input
<select class="u-full-width" name="country" id="country">
If you run the fiddle, you will see it works as expected.
document.querySelector('#generate-names').addEventListener('submit', loadNames);
// Execute the function to query the API
function loadNames(e) {
e.preventDefault();
// Read the values from the form and create the variables
const origin = document.getElementById('country').value;
const gender = document.getElementById('gender').value;
const amount = document.getElementById('quantity').value;
// Build the URL
let url = 'http://uinames.com/api/?';
// Read the origin and append to url
if (origin !== '') {
url += `region=${origin}&`;
}
console.log(url);
}
<div class="container">
<div id="content" class="content">
<h1>Generate Names</h1>
<form id="generate-names" action="#">
<div class="row">
<div class="six-columns">
<label for="country">Filter By Country:</label>
<select class="u-full-width" name="country" id="country">
<option value="">-- Select --</option>
<option value="argentina">Argentina</option>
<option value="brasil">Brasil</option>
<option value="colombia">Colombia</option>
<option value="costa rica">Costa Rica</option>
<option value="france">France</option>
<option value="italy">Italy</option>
<option value="mexico">Mexico</option>
<option value="portugal">Portugal</option>
<option value="united states">United States</option>
<option value="india">India</option>
<option value="japan">Japan</option>
</select>
<label for="gender">Gender:</label>
<select class="u-full-width" id="gender">
<option value="">-- Select --</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label>Number of names to generate</label>
<input type="number" id="quantity" class="u-full-width" min="5" max="15" value="5">
<input class="button-primary u-full-width" type="submit" value="Generate">
</div>
<div class="six-columns">
<div id="result"></div>
</div>
</div>
</form>
</div>
</div>
I have problem with onsubmit JavaScript function. I set validation for CVV and expiry date. When I enter only CVV it's submitted without entering date but when I enter date it's also asking CVV but in CVV case its not asking expiry date.
<form name="card" method="post" onsubmit="return validateexpiry()|| validate_cvv(document.card.cvv);">
<table>
<tr>
<td> Expiry Date
<td>
<td>
<select id="exMonth" title="select a month">
<option value="0">Month
</option>
<option value="01">January
</option>
<option value="02">February
</option>
<option value="03">March
</option>
<option value="04">April
</option>
<option value="05">May
</option>
<option value="06">June
</option>
<option value="07">July
</option>
<option value="08">August
</option>
<option value="09">September
</option>
<option value="10">October
</option>
<option value="11">November
</option>
<option value="12">December
</option>
</select>
<select id="exYear" title="select a year">
<option value="0">Year
</option>
<option value="2016">2016
</option>
<option value="2017">2017
</option>
<option value="2018">2018
</option>
<option value="2019">2019
</option>
<option value="2020">2020
</option>
<option value="2021">2021
</option>
<option value="2022">2022
</option>
<option value="2023">2023
</option>
<option value="2024">2024
</option>
<option value="2025">2025
</option>
<option value="2026">2026
</option>
<option value="2027">2027
</option>
<option value="2028">2028
</option>
<option value="2029">2029
</option>
<option value="2030">2030
</option>
<option value="2031">2031
</option>
</select>
</td>
<tr>
<td>
<span id="invalidexpiry">
</span>
</td>
</tr>
<tr>
<td>
CVV
<input type="text" name="cvv" class="cvv" onkeypress="return isNumber(event)" >
<span id="usernameError">
</span>
</td>
</tr>
<tr>
<td>
<div id="centreimg">
<input type="submit" name="S1" value="Submit response" />
</div>
</td>
</tr>
</table>
</form>
function validateexpiry()
{
var today, someday;
var exMonth=document.getElementById("exMonth").value;
var exYear=document.getElementById("exYear").value;
today = new Date();
someday = new Date();
someday.setFullYear(exYear, exMonth, 1);
if (someday
< today) {
document.getElementById('invalidexpiry').innerHTML="Invalid expiry date";
return false;
}
}
// cvv
function validate_cvv(cvv){
var myRe = /^[0-9]{3,4}$/;
if(cvv.value.match(myRe))
{
return true;
}
else (card.cvv.value.length==2)
{
document.getElementById('usernameError').innerHTML="Invalid CVV";//invalid cvv number
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Recharge</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="header.css" text="text/css" rel="stylesheet">
<script src="time.js" type="text/javascript"></script>
<script src="jquery-2.2.3.min.js" type="text/javascript"></script>
<style type="text/css"></style>
<body>
<form name="card" method="post" onsubmit="return validateexpiry()&& validate_cvv(document.card.cvv);">
<table>
<tr>
<td> Expiry Date<td>
<td>
<select id="exMonth" title="select a month">
<option value="0">Month</option>
<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select id="exYear" title="select a year">
<option value="0">Year</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
<option value="2026">2026</option>
<option value="2027">2027</option>
<option value="2028">2028</option>
<option value="2029">2029</option>
<option value="2030">2030</option>
<option value="2031">2031</option>
</select>
</td>
<tr><td><span id="invalidexpiry"></span></td></tr>
<tr><td>
CVV
<input type="text" name="cvv" class="cvv" onkeypress="return isNumber(event)" ><span id="usernameError"></span>
</td></tr>
<tr>
<td>
<div id="centreimg">
<input type="submit" name="S1" value="Submit response" />
</div>
</td>
</tr>
</form>
It's hard to give you a definite answer without seeing the code for validateexpirty and validate_cvv but my initial guess would be that your logic in validating is at fault:
onsubmit="return validateexpiry()|| validate_cvv(document.card.cvv);"
That should probably include && instead of ||.
The || operator works from left to right. That is, it will first evaluate validateexpiry() and if it returns true, rest of the expression will not be evaluated (because no matter what happens, the result will be true). If, on the other hand, it evaluates to false, only then the second part of the expression will be evaluated. This will keep on going until either a predicate returns true (in which case the expression will return true) or all predicates are evaluated to false (in which case the expression will return false).
EDIT: The answer is correct, the reason the answer doesn't work for you is because your CVV validation code is broken. After fixing up the HTML and JS snippets you posted in your question and comments here's what I have. It correctly works after fixing the errors.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Recharge</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css"></style>
<body>
<script>
function validateexpiry() {
var today, someday;
var exMonth=document.getElementById("exMonth").value;
var exYear=document.getElementById("exYear").value;
today = new Date();
someday = new Date();
someday.setFullYear(exYear, exMonth, 1);
if (someday < today) {
document.getElementById('invalidexpiry').innerHTML="Invalid expiry date";
return false;
}
return true;
}
function validate_cvv(cvv) {
var myRe = /^[0-9]{3,4}$/;
if(cvv.value.match(myRe)) {
return true;
} else {
document.getElementById('usernameError').innerHTML="Invalid CVV";
return false;
}
}
</script>
<form name="card" action="/" method="post" onsubmit="return validateexpiry()&& validate_cvv(document.card.cvv);">
<table>
<tr>
<td> Expiry Date<td>
<td>
<select id="exMonth" title="select a month">
<option value="0">Month</option>
<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select id="exYear" title="select a year">
<option value="0">Year</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
<option value="2026">2026</option>
<option value="2027">2027</option>
<option value="2028">2028</option>
<option value="2029">2029</option>
<option value="2030">2030</option>
<option value="2031">2031</option>
</select>
</td>
<tr><td><span id="invalidexpiry"></span></td></tr>
<tr><td>
CVV
<input type="text" name="cvv" class="cvv" ><span id="usernameError"></span>
</td></tr>
<tr>
<td>
<div id="centreimg">
<input type="submit" name="S1" value="Submit response" />
</div>
</td>
</tr>
</form>
</body>
</html>
Compare the corrected validation code to your version:
function validateexpiry()
{
var today, someday;
var exMonth=document.getElementById("exMonth").value;
var exYear=document.getElementById("exYear").value;
today = new Date();
someday = new Date();
someday.setFullYear(exYear, exMonth, 1);
if (someday < today) {
document.getElementById('invalidexpiry').innerHTML="Invalid expiry date";
return false;
}
}
function validate_cvv(cvv){
var myRe = /^[0-9]{3,4}$/;
if(cvv.value.match(myRe))
{
return true;
}
else (card.cvv.value.length==2)
{
document.getElementById('usernameError').innerHTML="Invalid CVV";
return false;
}
}
validateexpiry doesn't return if the value is correct, thus it returns undefined implicitly, which of course, evaluates to false in your onsubmit handler. There is also an error with how you create the selected date, it's always off by one but I didn't correct that.
validate_cvv has an outright syntax error. if ... else block's else doesn't take any conditions.
Should the validation be && instead of ||
onsubmit="return validateexpiry() && validate_cvv(document.card.cvv);"
Can you post also the validation made validateexpiry() and validate_cvv(document.card.cvv).
But my initial guest is that it should be
return validateexpiry() && validate_cvv(document.card.cvv);
Or your expiry date has default value 0 year and 0 month so validateexpiry might missed this one.
I am trying to get a landing page grab the URL parameters. I have two hidden fields in the form that match the parameter names, but I can't seem to get this to work.
I need to grab the URL Parameters, and have them send with the rest of the form. The form's method="POST">
I need to do this with JavaScript, not PHP.
THANKS!
For instance, a URL will look like this:
http://mywebsite.com/qualify/new/?AFFILIATE_ID=-1&SUB_1=Test#
Here is my form code:
<html>
<head>
<script>
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
Please Choose an Insurance Type
Private / Group Insurance
Medicare / Medicaid
Secondary Insurance
<input type="text" name="phone" placeholder="Phone Number" required="required">
<select value="State" name="state" style="width:100%;height: 35px!important; margin-top: 10px!important;">
<option value="">Please Choose a State:</option>
<option value="Alabama">Alabama</option>
<option value="Arizona">Arizona</option>
<option value="California">California</option>
<option value="Colorado">Colorado</option>
<option value="Connecticut">Connecticut</option>
<option value="Delaware">Delaware</option>
<option value="District Of Columbia">District Of Columbia</option>
<option value="Florida">Florida</option>
<option value="Georgia">Georgia</option>
<option value="Illinois">Illinois</option>
<option value="Indiana">Indiana</option>
<option value="Iowa">Iowa</option>
<option value="Kentucky">Kentucky</option>
<option value="Maine">Maine</option>
<option value="Maryland">Maryland</option>
<option value="Massachusetts">Massachusetts</option>
<option value="Michigan">Michigan</option>
<option value="Minnesota">Minnesota</option>
<option value="Missouri">Missouri</option>
<option value="Montana">Montana</option>
<option value="Nebraska">Nebraska</option>
<option value="New Hampshire">New Hampshire</option>
<option value="New Jersey">New Jersey</option>
<option value="New Mexico">New Mexico</option>
<option value="New York">New York</option>
<option value="North Carolina">North Carolina</option>
<option value="North Dakota">North Dakota</option>
<option value="Ohio">Ohio</option>
<option value="Oklahoma">Oklahoma</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Rhode Island">Rhode Island</option>
<option value="South Carolina">South Carolina</option>
<option value="Tennessee">Tennessee</option>
<option value="Texas">Texas</option>
<option value="Utah">Utah</option>
<option value="Virginia">Virginia</option>
<option value="Washington">Washington</option>
<option value="West Virginia">West Virginia</option>
<option value="Wisconsin">Wisconsin</option>
</select>
<input type="number" min="18" max="64" step="1" name="birthdate" placeholder="Age" required="required" style="margin-bottom: 8px!important;">
<input type="text" name="insuranceComp" placeholder="Insurance Company" required="required">
<input type="text" name="memberID" placeholder="Member ID or Group Policy" required="required">
<input type="text" name="RxBin" placeholder="Rx Bin Number" required="required">
<input type="text" name="PcnNumber" placeholder="PCN Number" required="required">
<input type="text" name="groupID" placeholder="Rx Group ID" required="required">
<input type="hidden" name="SUB_1" value="">
<input type="hidden" name="AFFILIATE_ID" value="">
<button class="submit" style="width: 100%;">Submit Now</button>
</form>
</body>
</html>
If you mean GET values you can do this by either echoing the whole form with the variables in the appropriate places like so;
<?php
echo'
<input type="text" name="phone" placeholder="Phone Number" required="required">
<select value="State" name="state" style="width:100%;height: 35px!important; margin-top: 10px!important;">
<option value="">Please Choose a State:</option>
<option value="Alabama">Alabama</option>
<option value="Arizona">Arizona</option>
<option value="California">California</option>
<option value="Colorado">Colorado</option>
<option value="Connecticut">Connecticut</option>
<option value="Delaware">Delaware</option>
<option value="District Of Columbia">District Of Columbia</option>
<option value="Florida">Florida</option>
<option value="Georgia">Georgia</option>
<option value="Illinois">Illinois</option>
<option value="Indiana">Indiana</option>
<option value="Iowa">Iowa</option>
<option value="Kentucky">Kentucky</option>
<option value="Maine">Maine</option>
<option value="Maryland">Maryland</option>
<option value="Massachusetts">Massachusetts</option>
<option value="Michigan">Michigan</option>
<option value="Minnesota">Minnesota</option>
<option value="Missouri">Missouri</option>
<option value="Montana">Montana</option>
<option value="Nebraska">Nebraska</option>
<option value="New Hampshire">New Hampshire</option>
<option value="New Jersey">New Jersey</option>
<option value="New Mexico">New Mexico</option>
<option value="New York">New York</option>
<option value="North Carolina">North Carolina</option>
<option value="North Dakota">North Dakota</option>
<option value="Ohio">Ohio</option>
<option value="Oklahoma">Oklahoma</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Rhode Island">Rhode Island</option>
<option value="South Carolina">South Carolina</option>
<option value="Tennessee">Tennessee</option>
<option value="Texas">Texas</option>
<option value="Utah">Utah</option>
<option value="Virginia">Virginia</option>
<option value="Washington">Washington</option>
<option value="West Virginia">West Virginia</option>
<option value="Wisconsin">Wisconsin</option>
</select>
<input type="number" min="18" max="64" step="1" name="birthdate" placeholder="Age" required="required" style="margin-bottom: 8px!important;">
<input type="text" name="insuranceComp" placeholder="Insurance Company" required="required">
<input type="text" name="memberID" placeholder="Member ID or Group Policy" required="required">
<input type="text" name="RxBin" placeholder="Rx Bin Number" required="required">
<input type="text" name="PcnNumber" placeholder="PCN Number" required="required">
<input type="text" name="groupID" placeholder="Rx Group ID" required="required">
<input type="hidden" name="SUB_1" value="'.$_GET['value1'].'">
<input type="hidden" name="AFFILIATE_ID" value="'.$_GET['value2'].'">
<button class="submit" style="width: 100%;">Submit Now</button>
</form>
';
?>
Alternatively you could echo only the hidden fields, like so;
<?php
echo'
<input type="hidden" name="SUB_1" value="'.$_GET['value1'].'">
<input type="hidden" name="AFFILIATE_ID" value="'.$_GET['value2'].'">
';
?>
Your conceptual approach seems reasonably sound, just a few implementation issues. The code might look something like this:
$(document).ready(function () {
if(window.location.search && window.location.search.indexOf('&') !== -1) {
var pairs = window.location.search.replace('?', '').split('&');
$.each(pairs, function (index, pair) {
var parameter = pair.split('=')[0];
var value = pair.split('=')[1];
if(parameter === 'AFFILIATE_ID' || parameter === 'SUB_1') {
$('input[name="' + parameter + '"]').val(value);
}
});
}
});
NOTE: this answer uses jQuery, which in this situation would probably be best for browser compatability, but I can post a pure JS solution if you need one.
Your code works. You just need to add the part that populates your form fields:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
var returnval = match && decodeURIComponent(match[1].replace(/\+/g, ' '));
// populate form fields
$("[name='"+name+"']").val( returnval );
return returnval;
}
// fire your function when the form submits
$(function(){
$('#contact-form').on('submit',function(){
getParameterByName('AFFILIATE_ID');
getParameterByName('SUB_1');
});
});
I'm very new to javascript, so finding it hard to see where I went wrong. For some reason my functions aern't working. Any help would be appreciated. I've tried using them in an external js file, head / body and nothing seems to work. The mistake is either with the functions or with calling them.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Nicky's</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
function CheckfName() {
var name=0;
var checknames=isNaN(name);
window.alert("Please use only letters in the name space");
return false; }
function checkc number() {
var cellN=0;
var numBercheck=isNan(cellN);
window.alert("Please use only numbers in the cell number space");
return false }
function confirmBooking() {
if(document.forms[0].firstName.value==0
|| document.forms[0].lastName.value.value==0) {
window.alert("Please fill in your First and Last name");
return false; }
if(document.forms[0].firstName.value==""
|| document.forms[0].lastName.value=="") {
window.alert("Please fill in your first and last name");
return false; }
else if(document.forms[0].areaCode.value==""
|| document.forms[0].threeMiddlenumbers.value==""
|| document.forms[0].LastfourNumbers.value=="") {
window.alert("Please enter your cell number.");
return false; }
else if(document.forms[0].hairstyles.value=="Setdefault"
|| document.forms[0]servCes.value=="Setdefault") {
window.alert("Please select hairstyle type");
return false; }
else if(document.forms[0].day.value=="SelectDay"
|| document.forms[0].month.value=="SelectMonth"
|| document.forms[0].time.value=="Selectime") {
window.alert("Please select the Day, Month and Time!");
return false; }}
function resetBooking() {
var reset=window.confirm("Are you sure that you want to reset
your booking information?");
if(reset==true) {
return true;
return false; }}
</script>
</head>
<body>
<div class="wrapper">
<div id="header">
</div>
<ul id="navlist">
<li>Home</li>
<li>Booking</li>
<li>Services</li>
<li>Contact Us</li>
</ul>
<div id="article">
<form method="get" action="BookingProcessor.html" enctype="application/x-www-form-urlencoded"
onsubmit="return confirmBooking();" onreset="return resetBooking();">
<p>First Name
<input type="text" onchange="CheckfName()" name="firstName" maxlength="35" size="35"
style="margin-left:20px;"/>
</p>
<p>Last Name
<input type="text" onchange="CheckfName()" name="lastName" maxlength="35" size="35"
style="margin-left:28px;"/>
</p>
<p>Cell Number
<input type="text" onchange="CheckCnumber()" name="areaCode" size="3" maxlength="3"
style="margin-left:15px;">
<input type="text" name="threeMiddleNumbers" size="3" onchange="CheckCnumber()"
maxlength="3"/>
<input type="text" name="LastfourNumbers" size="4" onchange="CheckCnumber()"
maxlength="4"/>
<p>Hairstyle Type
<select name="hairstyles">
<option value="Setdefault">Select Hairstyle</option>
<option value="none">None</option>
<option value="straightBack">Straight back long</option>
<option value="Bondings">Bondings</option>
<option value="hairByhair">Hair by hair</option>
<option value="blowNcut">Blow and Cut</option>
<option value="bopCorn">Bopcorn</option>
<option value="twistLong">Twist Long</option>
<option value="dreadS">Dreads</option>
</select
</p>
<select name="day">
<option value="SelectDay">Select Day</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="month">
<option value="SelectMonth">Select Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<select name="time">
<option value="Selecttime">Select Booking Time</option>
<option value="8to9">Between 8am and 9am</option>
<option value="9to10">Between 9am and 10am</option>
<option value="10to11">Between 10am and 11am</option>
<option value="11to12">Between 11am and 12pm</option>
<option value="12to13">Between 12pm and 13pm</option>
<option value="13to14">Between 13pm and 14pm</option>
<option value="14to15">Between 14pm and 15pm</option>
<option value="15to16">Between 15pm and 16pm</option>
<option value="16to17">Between 16pm and 17pm</option>
<option value="17to18">Between 17pm and 18pm</option>
</select>
<p>If there are any other requirements, please specify in the text area below</p>
<p>
<textarea name="Requirement" cols="40" rows="3" style="overflow: hidden;">
</textarea>
</p>
<p>
<input type="submit" value="Place a Book">
<input type="reset" value="Reset a Form">
</form>
</div>
</div>
</body>
</html>
Here are some issues I've found.
function checkNumber() {
var cellN=0;
var numBercheck=isNan(cellN);
window.alert("Please use only numbers in the cell number space");
return false;
}
use checkNumber instead of "checkc number", also no semicolon after return statement
function resetBooking() {
var reset=window.confirm("Are you sure that you want to reset your booking information?");
if(reset==true) {
return true;
}
return false;
}
if statement is wrong (it had 2 returns )
You have a typo in your function name. There should be no space.
function checkc number() {
var cellN=0;
var numBercheck=isNan(cellN);
window.alert("Please use only numbers in the cell number space");
return false }
Change the name to function checkcnumber().
Also you are missing semicolon in return statement.