Need to validate form before sending - javascript

I am trying to send a form to email but I wanted the name field to be validated (if no content then don't send)
I cannot get it validate and then end through the php script I have working correctly
I have created a jsfiddle at the following link
Can someone help please?
$(document).ready(function () {
$('.form-horizontal').on('submit', function (e) {
e.preventDefault();
var name = $('#name').val();
if (!name) {
showError();
}
else {
$('#contact-form').submit();
}
});
function showError() {
$('.tyler-error').show();
}
});

Working fiddle
In your fiddle, you didn't select jQuery from the library dropdown.
Secondly, you should avoid submitting the form from within the submit handler, instead just preventDefault if there is a validation error.
$('.form-horizontal').on('submit', function (e) {
var name = $('#name').val();
if (!name) {
showError();
e.preventDefault();
}
});
If you really want to keep the code as it was, you need to call the forms submit function, not the jQuery submit function:
$('#contact-form')[0].submit();
// or
$('#contact-form').get(0).submit();
Here, [0] or .get(0) is giving you the plain JavaScript DOM element with no jQuery wrapper, and with this you can call submit().

HTML5 provides input validation, you can set in order to tell the browser that your html view is HTML5.
//Set your doctype for HTML5.
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<form id="the_form">
//here html5 will not submit if the box is empty or does not meet the email
//addres format.
<input type="email" name="email" id="email" placeholder="Enter email..">
<input type="submit" value="send">
</form>
</body>
</html>
If you dont want to use HTML5, you could also make a simple javascript code to not submit if the input is empty.
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = init();
function init(){
//get form.
var form = document.getElementById("the_form");
form.onsubmit = email_validation;
}
function email_validation(){
email = document.getElementById("email");
if(email.value == ''){
//return false to avoid submission.
return false;
}
else{
//do whatever code.
}
}
</script>
</head>
<body>
<form id="the_form">
<input type="text" name="email" id="email" placeholder="Enter email..">
<input type="submit" value="send">
</form>
</body>
</html>
with this way, your email will be validated before is sent, hope this work for you.

Related

Javascript addEventListener leads to incorrect result

I have a problem as I try to addEvenrListener to the form to validate the user input. However, there is something wrong with the code as it keeps showing "All done" even when I left blank the input or the input contains number inside. Can you guys let me know me where is the problem? Furthermore, what is the difference between onsubmit and addEventListener? Is there any way simpler to do this? I just start learning JavaScript so I just want to build my knowledge step by step starting from the bottom. Thank you so much!
var check=document.getElementById("check");
var name=document.getElementById("name");
var reg = /^[a-zA-Z]+$/;
function ipt(){
if(name.value !== ""){
if(!reg.test(name.value)){
alert("Number not allowed")
}
else{
alert("All done");
}
}
else{
alert("Please enter your name");
}
}
check.addEventListener("submit", ipt());
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
<script src="./check.js" defer></script>
</head>
<body>
<form name="check" id="check">
<label for="name">Name</label>
<input type="text" id="name" name="name" value="">
<button type="submit">Submit</button>
</form>
</body>
</html>
This happens because you invoke the function with parenthesis () at the event listener, invoke the function without parenthesis.
Try creating your "check" and "name" variables inside the function ipt(), so immediately you submit the form, it will take the info that you previously typed in the input.
Creating your variables outside the function, the result will be undefined for the input value because js creates them as soon as the page is created and when you submit, those variables were already created at the beginning without any info.
here some official docs from MDN about submit eventListener.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Add your script at the bottom of the body, it gives the HTML the time to load before de Javascript code is executed.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
</head>
<body>
<form name="check" id="check">
<label for="name">Name</label>
<input type="text" id="name" name="name" value="">
<button type="submit">Submit</button>
</form>
<script src="./check.js" defer></script>
</body>
</html>
And here your Js file, add the event as an argument to your "ipt" function.
var reg = /^[a-zA-Z]+$/;
function ipt(event) {
event.preventDefault();
var check = document.getElementById("check");
var name = document.getElementById("name");
if (name.value !== "") {
if (!reg.test(name.value)) {
alert("Number not allowed")
}
else {
alert("All done");
}
}
else {
alert("Please enter your name");
}
}
check.addEventListener('submit', ipt);
Hope it works for You. Regards!

Can't get input validation Javascript to work

Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.

How to verify the elements of a form in Javascript then Move to a PHP page?

I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}

How do I manually test JavaScript?

I'm trying to learn javascript by making a simple price checking website using the Best Buy products API.
How do I "run" the javascript? My form takes in a product ID number (the SKU) and sends it to validateSKU() on submit. The function processData(data) searches for the product using the SKU.
Nothing is happening when I test the site, and any help would be great; thanks!
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()">
<input id="SKU" name="SKU" required="" type="text">
<label for="SKU">SKU</label>
<input id="email" name="email" type="email">
<label for="email">Email</label>
<input class="button" id="submit" name="submit" type="submit">
</form>
<script>
function validateSKU() {
var SKU = document.forms["bestBuyForm"]["SKU"].value;
var bby = require('bestbuy')('process.env.BBY_API_KEY');
var search = bby.products('sku=' + SKU);
search.then(processData);
}
function processData(data) {
if (!data.total) {
console.log('No products found');
} else {
var product = data.products[0];
console.log('Name:', product.name);
console.log('Price:', product.salePrice);
}
}
</script>
</body>
</html>
Use web console to see what does happen and read about the console API.
Try to bind validateSKU with HTML element addEventListener method. Also you should prevent default form behaviour which cause page reloading on submit. Call event.preventDefault().
Working example code:
<html>
<form id="someForm">
...
<button type="submit">Submit</submit>
</form>
<script>
function validateSKU(event) {
console.log('IT works');
event.preventDefault();
// ...here your code
}
var form = document.getElementById('someForm');
form.addEventListener('submit', validateSKU, false);
</script>
</html>

div tag not being updated

I have created a simple application which connects to a rest api, as follows:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" >
</script>
<title></title>
</head>
<body>
<h1 id="header">A headline</h1>
<div id = "info"></div>
<p1 id = "p1">p1</p1>
<form id="name" name="name">
Please enter a switch: <input type="text" name="switch" id = "switch">
<input type="submit" value="submit" name="submit" id="submit">
</form>
<script>
$(document).ready(function() {
$('#name').submit(function() {
alert('submitted');
var switchName = $('#switch').val();
$.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches(data));
});
});
function processSwitches(data) {
alert('processSwitches');
var infoHTML = '<p>Switch Name: ' + data.switchName +'</p>' ;
alert(infoHTML);
$('#info').html(infoHTML);
$('#header').html('<h1>Switches</h1>');
}
</script>
</body>
</html>
It runs, and will return an alert with the infoHTML string correctly, but I can't figure out why it won't update the div tag with id info.
Could anyone help?
Thanks.
You're invoking the processSwitches function inside the $.getJSON function. You should pass only the name of that function - without the (data) part:
$.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches);
Simply, this:
processSwitches
instead of this:
processSwitches(data)
EDIT:
You also forgot to prevent the form from submiting. Simply add return false at the end of the submit event handler:
$('#name').submit(function() {
alert('submitted');
var switchName = $('#switch').val();
$.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches);
return false;
});
It looks like you're submitting the form. Upon form submition data is lost.
Try adding
return false
after
$.getJSON(... )
In the fiddle it works http://jsfiddle.net/K3ZKA/ check your console for errors!
strings are undefined but doesen't matter

Categories

Resources