How to add multiple Email addresses in text input HTML - javascript

In HTML5 in Used this code, i want user to be able to add multiple email address in input box...
<div class="modal-body row-fluid" align="left">
<span class="loader-gif" style="display:none;"><img src="<?php echo $baseURL?>/watever/img/ajax-loader-horizontal.gif"></span>
Email:
<input type="email" multiple="multiple" autofocus="" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$" style="display:none;width:91%;cursor:text;" />Links:
<input type="text" readonly="readonly" style="display:none;width:91%;cursor:text;" />
<span class="message" style="display:none;"></span>
</div>
I have added Multiple property in input type="email", still i am not able to add more than one email address in my browser,
i am using, firefox latest version for testing. I just want to know, what is the way, to allow user to add multiple email addresses in that input box?
and how to later retrieve those values using Javascript.

try this, include the jquery and validate js file as per your file location
<html>
<head>
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
jQuery.validator.addMethod("multiemail", function (value, element) {
if (this.optional(element)) {
return true;
}
var emails = value.split(','),
valid = true;
for (var i = 0, limit = emails.length; i < limit; i++) {
value = emails[i];
valid = valid && jQuery.validator.methods.email.call(this, value, element);
}
return valid;
}, "Please separate email addresses with a comma and do not use spaces.");
$("#emailFrm").validate({
errorElement:'div',
rules: {
emails: {
required: true,
multiemail:true
}
},
messages:
{
emails: {
required:"Please enter email address."
}
}
});
});
</script>
</head>
<body>
<form method="post" id="emailFrm">
<input type="text" name="emails" />
<input type="submit" name="submit" value="submit">
</form>
</body>
demo click here

Do not use the pattern attribute for e-mail validation. The browsers validate an e-mail address in an e-mail input field.
Himanshu97, you did not specify how you entered the e-mail addresses. Browsers expect them to be separated by comma, not just space (seems weird for me).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>e-mail addresses</title>
</head>
<body>
<form method="post">
<fieldset>
<legend>e-mail addresses</legend>
<label>e-mail addresses
<!-- use email type to enable browser to validate and display error messages
also browsers can display an optimized "keyboard"
do no use pattern, browsers have a build in pattern -->
<input type="email" name="emailAddress" id="emailAddress" value="e#e"
placeholder="e#e, mail#example.com, mail#example.org" autofocus multiple required>
</label>
<p>is valid: input is <span id="isValid">not</span> valid</p>
<p>splitted input:</p>
<ol id="splittedInput"></ol>
<button type="submit">submit</button>
</fieldset>
</form>
<script>
const MAIL_INPUT = document.getElementById('emailAddress');
const IS_VALID = document.getElementById('isValid');
const SPLITTED_INPUT = document.getElementById('splittedInput');
MAIL_INPUT.oninput = (input) => {
IS_VALID.innerText = input.srcElement.validity.valid ? '' : 'not';
const SPLITTED = input.srcElement.value.split(',');
let addresses = [];
let list = [];
for (const SPLIT of SPLITTED)
addresses.push(SPLIT.trim());
for (const ADDRESS of addresses.sort())
list.push(newListElement(ADDRESS));
SPLITTED_INPUT.replaceChildren(...list);
}
function newListElement(content) {
let li = document.createElement('li');
li.innerText = content + ' — ' + (validEmailAddress(content) ? 'valid' : 'invalid');
return li;
}
function validEmailAddress(emailaddress) {
// this regex does not validate correctly. Try abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopq#a.aa (invalid)
return /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailaddress);
}
</script>
</body>
</html>

Related

how to assign value to input function using javascript

I was trying to code a basic login web program with javascript when I discovered a problem. I can't assign value to input function using js. So now I can't use if else to create a basic login. here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="index.css">
<script src="index.js"></script>
</head>
<html>
<body>
<h1>Login</h1>
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47">
<br>
<br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47">
<br>
<button type="button" onclick="login()" class="login">Login</button>
<script>
let username = 'username';
let password = 'password';
function login() {
if (username == a88, password == a89) {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
</script>
</div>
</body>
</html>
please help me
Seems like the input values are not being read from the page. In order to read the input values, you will first be required to grab the input DOM elements from the page.
The input fields have id attribute assigned to them which could be used to extract these elements.
<input ... id="username" ...>
<input ... id="password" ...>
You may use query selectors for that:
# Extract username input field
const usernameInputField = document.querySelector('#username')
# Extract password input field
const passwordInputField = document.querySelector('#password')
In the above snippet, document.querySelector is used to extract any DOM elements from the webpage. This function takes in the CSS selector as a parameter. Here, #username and #password are the CSS selectors for username and password fields respectively. The # sign signifies to select using the DOM element's ID.
Once we have the input fields, all we are left to do is to get the current values from these fields:
# Get current input value of username input field
const username = usernameInputField.value
# Get current input value of password input field
const password = passwordInputField.value
We use the value property of the input element to grab the current input value.
Solution:
// Grab the input fields from the page
const usernameInputField = document.querySelector('#username')
const passwordInputField = document.querySelector('#password')
function login() {
// Grab current input values
const username = usernameInputField.value
const password = passwordInputField.value
// The remaining code below stays the same
if (username === a88, password === a89) {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
In the login() function, we take the current value of the input fields and do the validation as it was handled previously. Note that, we do that inside the function itself to ensure that we have the latest value from the input fields.
The document.getElementById() method is used to select HTML elements by id. It is used as the rvalue of the value property to read the value of the HTML element.
/* The following method is used to select HTML elements based on the id attribute. */
const userNameElem = document.getElementById('username');
const passwordElem = document.getElementById('password');
const submitButton = document.getElementById("submit");
/* You can define the user name as a string as follows. */
const username = 'george';
/* You can define the user password as a string as follows. */
const password = '12345';
/* It is not recommended to assign a function to the "onclick" attribute in an HTML file. */
submitButton.addEventListener("click", function() {
if(userNameElem.value == username && passwordElem.value == password) {
alert("TRUE");
}
else {
alert("FALSE");
}
});
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47"><br><br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47"><br>
<button type="button" id="submit" class="login">Login</button>
</div>
The below code may help you. And I think Web forms — Working with user data will help you more.
function login() {
const username = document.getElementById("username").value
const password = document.getElementById("password").value
// I change "a88", "a89" to strings, not variables.
// Change back if I'm wrong.
if (username == "a88", password == "a89") {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
<h1>Login</h1>
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47">
<br>
<br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47">
<br>
<button type="button" onclick="login()" class="login">Login</button>
</div>
/* "onclick" function invoked from HTML file. */
function submit() {
/* sample user name */
const username = 'tony';
/* sample password */
const password = '1234';
const userNameElem = document.getElementById('username');
const passwordElem = document.getElementById('password');
const submitButton = document.getElementById("submit");
if(userNameElem.value == username && passwordElem.value == password) {
alert("TRUE");
}
else {
alert("FALSE");
}
};
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47"><br><br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47"><br>
<button type="button" id="submit" class="login" onClick="submit()">Login</button>
</div>
You can pass values to the functions as parameters within brackets. And also whenever you try to compare strings, use quotations to wrap your strings. In your case values of a89 and a88 should be within quotes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="index.css">
<script src="index.js"></script>
</head>
<html>
<body>
<h1>Login</h1>
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47">
<br>
<br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47">
<br>
<button type="button" onclick="login()" class="login">Login</button>
<script>
let username = 'username';
let password = 'password';
function login(username,password) {
if (username === 'a88', password === 'a89') {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
</script>
</div>
</body>
</html>
<script>
function login() {
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
if ((username == "a88", password == "a89")) {
alert("Thành công");
} else {
alert("không thàng công");
}
}
</script>

Input field value 'undefined' even with value in it

I am trying to make a login form. for some reason i am getting an error my input is 'null' or undefined even when I fill out the form and submit
<form name ="loginform" onSubmit ={validate()} method ="post">
<p>Email</p>
<input id = "mail" type = "email" name = "usr" placeholder = "Enter Email" required></input>
<p>Password</p>
<input id ="pass" type ="password" name ="pword" placeholder = "Enter Password" required></input>
<input type = "submit" name ="" value ="Login" ></input> <br />
<a id ="demo" href ="#" style={{color:'white'}} >Forget Password?</a><br />
<a href = "#" style ={{color:'white'}}>need help?</a>
</form>
function validate(){
var un =document.getElementById("mail").value;
var pw = document.getElementById("pass").value;
var usernames = "username";
var passwords = "password" ;
if ((usernames === un) && (passwords === pw)) {
window.location = " index.js ";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
-Here is the function and I get this error: TypeError: Unable to get property 'value' of undefined or null reference. any help is apprectaed
Try the following changes:
in your var username use var usernames= "email#test.com"; as your input is an email.
While adding CSS style on each line is considered bad practice, you can do it with this syntax: style = "color:white" and add, change whatever attributes you want to change.
NOTE: White text color on white page will hide it for you.
Various html errors, I suggest use test your HTML code here every time: https://validator.w3.org/
Here is the final document I have for you:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<!-- <meta name="viewport" content="width=device-width, initial-scale=1"> -->
<!-- <link rel="stylesheet" type="text/css" media="screen" href="main.css"> -->
<script>
function validate() {
var un = document.getElementById("mail").value;
var pw = document.getElementById("pass").value;
var usernames = "email#test.com";
var passwords = "password";
if ((usernames === un) && (passwords === pw)) {
//window.location = " index.js ";
//return false;
alert("Login was Succesful"); // GOES HERE IF LOGIN WAS SUCCESSFUL
}
else {
alert("Login was unsuccessful, please check your username and
password");
}
}
</script>
</head>
<body>
<form name="loginform" onSubmit={validate()} method="post">
<p>Email</p>
<input id="mail" type="email" name="usr" placeholder="Enter Email" required>
<p>Password</p>
<input id="pass" type="password" name="pword" placeholder="Enter Password"
required>
<input type="submit" name="Login" value="Login"><br />
<a id="demo" href="#" style="color: white">Forget Password?</a><br />
need help?
</form>
</body>
</html>

Form Validation not responding correctly

I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.

HTML onsubmit event is not calling the JavaScript function

I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>

prevent form from submitting not working, JavaScript

Hello and thank you for your time.
I have a form with the id payment and a submit button, but there seems to be a mistake in my JavaScript, as I only get the alert message but the page still submits if I input a wrong name like a row of hash symbols #######. the code below is exactly how it is in my file.
// form validation, makes sure that the user inputs the correct data types.
function validateinput(event){
var email = document.getElementById('email').value;
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var message = document.getElementById('message').value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
var firstnameFilter = /^([" "a-zA-Z.-])+$/;
var lastnameFilter = /^([" "a-zA-Z.-])+$/;
var messageFilter = /^([" "a-zA-Z0-9_.-])+$/;
if (!emailFilter.test(email)) {
alert('!Enter a email. Or enter a valid email address.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!firstnameFilter.test(firstname)) {
alert('!Enter a first name. Or enter a valid name.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!lastnameFilter.test(lastname)) {
alert('!Enter a last name. Or enter a name., only letters');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!messageFilter.test(message)) {
alert('!Enter a message.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
have also tried other methods thought they do not seem too work on this page but works on others ?
Like changing the var names and id,s in this one i am using on my contact page
function validateinput(event){
var address1 = document.getElementById('address1').value;
var postcode = document.getElementById('postcode').value;
var address1Filter = /^([" "a-zA-Z0-9_.-])+$/;
var postcodeFilter = /^([" "a-zA-Z0-9_.-])+$/;
var formValid = true;
if (!address1Filter.test(address1)) {
alert('!Enter an address. Or enter a valid address., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
if (!postcodeFilter.test(postcode)) {
alert('!Enter a postcode. Or enter a valid postcode., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
So what am I doing wrong ?
the html
<!doctype html>
<!-- name: Edwin martin -date: 30/11/2015 -task: a form with split up inputs using the
<fieldset> & <legend> tags -->
<html lang="en">
<head>
<title>contact</title>
<script type="text/javascript" src="scripts/contact2.js"> </script>
<!-- ensures the document is using the correct char set -->
<meta charset="utf-8">
<meta name="description" content="contact page">
<link rel="icon" href="images/fav.png" type="image/png"/>
<!--
The below section looks like a comment, but it's a conditional include statement.
It's ignored by all browsers except IE9. html5shiv is a library that fixes some HTML5
IE bugs.
-->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- pulls in the styles sheet -->
<link rel="stylesheet" href="styles/indexstyles.css">
</head>
<body onload="main()">
<!-- start of the form, id form sets the position, size, border style and color -->
<div id="form2">
<!-- sets the link position, list and text style of the header, id head color sets the background color for the division around the header -->
<div id="head">
<header id="headcolor">
<div id="toplinks">
<ul>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="Index" onclick="location.href='index.html'"> </li>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="order" onclick="location.href='order.html'"> </li>
</ul>
</div> <br>
<br>
</header>
<h1 id="title"> Contact </h1>
<p> southampton solent pizzas: southampton solent university branch. E Park Terrace, Southampton, Hampshire SO14 0YN </p>
</div>
<div id="map"> </div>
<!-- id payment sets the input boxs background color , position and border for invaild - vaild -->
<form id="payment">
<!-- Contact Information section -->
<fieldset>
<legend> Personal Information </legend>
<p> <label> First Name(*): </label> <input type="text" name="first_name" id="firstname" placeholder="enter a first name" class="add1"></p>
<p> <label> Last Name(*): </label> <input type="text" name="last_name" id="lastname" placeholder="enter a last name" class="add1"></p>
<p> <label> Email(*): </label> <input type="text" name="email" id="email" placeholder="enter a email" class="add1"></p>
<p> <label>Phone Number: </label> <input type="text" name="phone" id="phone"></p>
<p> <label> message(*): </label> <input type="text" name="message" id="message" placeholder="enter your message" class="add1"></p>
</fieldset>
<!-- Submit button -->
<input type="submit" class="submit_button">
<input type="reset" class="reset_button">
</form>
</div>
<script type="text/javascript" src="scripts/contact.js"> </script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>
i also have another JS script as you can see from the two different links. but even if i remove that link - code there form still submits with the wrong input, as this code just reads a empty input
//onload callback function
function main() {
console.log("in main function");
var myForm = document.getElementById("payment");
myForm.addEventListener("submit",validateForm);
}
//validate callback function
function validateForm(event) {
var formValid = true;
var myForm = document.getElementById("payment");
if (myForm.first_name.value == "") {
formValid = false;
//display error message
document.getElementById("firstname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.last_name.value == "") {
formValid = false;
//display error message
document.getElementById("lastname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.email.value == "") {
formValid = false;
//display error message
document.getElementById("email").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.message.value == "") {
formValid = false;
//display error message
document.getElementById("message").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
}
document.getElementById('payment').addEventListener("submit", validateinput), the problem is that you want to pass an argument to the validateinput method, but you can't do it that way, to pass arguments to a callback method reference, you should wrap it in an anonymous function like this.
document.getElementById('payment').addEventListener("submit", function(event) {
validateinput(event);
});
I think you're over complicating your Javascript. If you change your submit to call the function directly you'll have an easier time handling the negative states.
<input type="submit" onclick="return validateinput();" class="submit_button">
You'll need to modify the validateinput function slightly since you won't have event being passed in anymore.

Categories

Resources