I am just practicing js. I am trying to make a very simple validation in form but it came with, as i was expecting, an error.
Here's my code :
var form = document.getElementById('form');
var name = document.getElementById('name');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
if (name.value == "")
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
The problem is that, it doesn't validate it. Every time it returns true on submitting but when i replace the " name.value" with "email.value" the code works. I don't know now what's the problem actually. If someone could help me..
It looks like the input with id name is not created in DOM by the time of JavaScript execution.
You can resolve that by putting the code in the window.onload code block or inside the form.onsubmit
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c) {
var name = document.getElementById('name');
if (name.value == "") {
error.innerHTML = "Error Submiting Form !";
return false;
} else {
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
};
handlingForm();
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
Your variable called name is a problem. It's not working because name is a predefined identifier in some implementations. Though it's not a reserved keyword, it's best practice to avoid using it as a variable name.
Rename it to name_ (or almost anything else) and it will work.
If name.value has no value, it is undefined. So undefined !== "", which is why it will never be true. Just do a null check for name.value. Also, you need to move name inside of that function since the first time it is called, value will always be undefined:
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
var name = document.getElementById('name');
if (!name.value)
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
Try this:
window.onload = handlingForm();
Why your function has c parameter?
This is due to a quirk of how global variables are handled in web pages. Each one is treated as a property of the window object, so when you assign to email, you're actually creating and assigning to window.email, and so on.
However, some properties of the window object already exist and have special meaning to the browser, such as window.location (the current URL) and window.name (used in cross-frame link targets).
To see it in practice, do this in the global scope (outside any function):
var location; // should be undefined, right?
alert(location); // but it's actually window.location
Because of the special meaning of window.name, anything you assign to it (or to global name) will be converted into a string. The element that you try to store becomes a string, and so no longer works as an element.
To fix it, simply move your code into a function, so that the variables are local and no longer have this strange behaviour. You can use your window.onload function for this.
Related
I have one simple form which have two fields called first name with id fname and email field with email. I have submit button with id called submit-btn.
I have disabled submit button using javascript like this
document.getElementById("submit-btn").disabled = true;
Now I am looking for allow submit if both of my fields are filled.
My full javascript is like this
<script type="text/javascript">
document.getElementById("submit-btn").disabled = true;
document.getElementById("submit-btn").onclick = function(){
window.open("https://google.com",'_blank');
}
</script>
I am learning javascript and does not know how I can do it. Let me know if someone here can help me for same.
Thanks!
Id propose something like this
Use a block, which encapsulates the names of variables and functions inside the block scope
Make small functions, which do just one thing
Prefer addEventListener over onclick or onanything
There are two types of events you could use on the inputs: input and change. input will react on every keystroke, check will only react, if you blur the input element
I added a check for validity to the email field with checkValidity method
{
const btn = document.getElementById("submit-btn");
const fname = document.getElementById("fname");
const email = document.getElementById("email");
deactivate()
function activate() {
btn.disabled = false;
}
function deactivate() {
btn.disabled = true;
}
function check() {
if (fname.value != '' && email.value != '' && email.checkValidity()) {
activate()
} else {
deactivate()
}
}
btn.addEventListener('click', function(e) {
alert('submit')
})
fname.addEventListener('input', check)
email.addEventListener('input', check)
}
<form>
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="submit-btn" value="Submit">
</form>
This is the simplest solution I can imagine:
myForm.oninput = () => {
btn.disabled = fname.value == '' || email.value == '' || !email.checkValidity();
}
<form id="myForm">
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="btn" value="Submit" disabled>
</form>
Personally, I prefer to use regex to check the e-mail, instead of checkValidity(). Something like this:
/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(email.value);
I am using a jQuery for mobile number validation without page refresh on submit button but it is not working and when I click the submitbutton. But with page refresh it works.
Here is my code:
index.html
<html>
<head>
<title>Submit Form Without Refreshing Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/refreshform.css" />
<script src="js/fresh.js"></script>
</head>
<body>
<div id="mainform">
<!-- Required div starts here -->
<form id="form">
<label>First Name:</label>
<br/>
<input type="text" id="fname" placeholder="First Name"/><br/>
<br/>
<label>Last Name:</label>
<br/>
<input type="text" id="lname" placeholder="Last Name"/><br/>
<br/>
<label>MobliNo:</label>
<br/>
<input type="text" id="mobile" placeholder="Your MobNo"/><br/>
<br/>
<label>ConfirmMobliNo:</label>
<br/>
<input type="text" id="remobile" placeholder="Confirm MobNo"/><br/>
<br/>
<label>Email:</label>
<br/>
<input type="text" id="email" placeholder="Your Email"/><br/>
<br/>
<input type="button" id="submit" value="Submit" onclick = "return Validate()"/>
</form>
</div>
</body>
</html>
refresh.js
$(document).ready(function(){
$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
var remobile = $("#remobile").val();
var email = $("#email").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("refreshform.php",{ fname1: fname, lname1: lname, mobile1: mobile, remobile1: remobile, email1: email},
function(data) {
alert(data);
$('#form')[0].reset(); //To reset form fields
});
});
});
function Validate() {
var mobile = document.getElementById("mobile").value;
var pattern = /^\d{10}$/;
if (pattern.test(mobile)) {
alert("Your mobile number : " + mobile);
return true;
}
alert("It is not valid mobile number.input 10 digits number!");
return false;
}
What should I do to achieve validation without page refresh?
$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
should be
$('#form').submit(function(event){
event.preventDefault();
if (Validate())
{
// Do the posting
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
or *)
$('#form').on('submit', function(event){
event.preventDefault();
if (Validate())
{
// Do the posting
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
By including event.preventDefault() in the event handler, you block the default action for the element that triggered the event. In this case, the default action is submitting the form, so without this change, the form will still be submitted in the normal way, after it is submitted through AJAX.
*) Side note: on is a bit more flexible for binding events. You can also specify a selector as the second parameter. This way, you can set an event handler in the document (or another containing element), which will automatically be called for events on any child element that matches the given selector. This is especially useful if you have dynamic pages where elements are added or removed, because you won't have to add the event handlers every time you add an element. In this particular case it won't matter much, but I thought I'd let you know. The syntax for that is:
$(document).on('submit', '#form', function(event){
Do it in a slight different way. Remove
onclick = "return Validate()"
from the button and put that inside the click function like this
$("#submit").click(function(){
var valid = Validate();
if(valid){
/// Then your rest of process here.
}
});
Hope that works.
This will just check whether the phone number has 10 digits
function Validate() {
var mobile = document.getElementById("mobile").value;
var remobile = document.getElementById("remobile").value;
if(isNaN(mobile) || isNaN(remobile)){
alert("Invalid. Mobile and re mobile should be numbers only.");
return false;
}
if(mobile.length != 10){
alert("Invalid number. It should be 10 digits only.");
return false;
}
if(remobile.length != 10){
alert("Invalid Re mobile number. It should be 10 digits only.");
return false;
}
if(mobile != remobile){
alert("Mobile and remobile does not match!");
return false;
}
alert("Valid Number.");
return true;
}
in you form use:
<form id="form" onsubmit="return Validate();">
and button just submit:
<input type="submit" id="submit" value="Submit" />
in your js validate code instead of return true
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
var remobile = $("#remobile").val();
var email = $("#email").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("refreshform.php",{ fname1: fname, lname1: lname, mobile1: mobile, remobile1: remobile, email1: email},
function(data) {
alert(data);
$('#form')[0].reset(); //To reset form fields
});
return false;
in this case you will submit form without page refresh
function Validate() {
var mob = /^[1-9]{1}[0-9]{9}$/;
if (mob.test($.trim($("#<%=mobile.ClientID %>").val())) == false) {
alert("Please enter valid mobile number.");
$("#<%=mobile.ClientID %>").focus();
return false;
}
I am validating the dates in below function. If the validation fails, then the form should not get submitted. I tried returning false in form onsubmit but it still gets submitted. However, Validation is working fine and getting the alert that I put in the function. Any help to stop submitting the form if validation fails.
<script>
function dateCheck()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
document.getElementById('name4').focus();
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setFullYear(parse_sDate.getFullYear() + 1);
if(parse_eDate >= parse_sDate)
{
alert("End date should not be greater than one year from start date");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return dateCheck()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
Just a comment:
If your listener passes a reference to the form, you can access the controls by name or ID:
<form onsubmit="return dateCheck(this)">
then:
function dateCheck(form) {
var start = form.name3.value;
...
}
Note that you should declare variables, otherwise they will become global at the point they are assigned to. Also, you should check the values in the controls before passing them to the compare function (and display a message asking the user to enter a valid value if they aren't).
function dateCheck(form) {
var start = form.name3.value;
var end = form.name4.value;
var valid = compare(start, end);
if (!valid) form.name4.focus();
return false;
}
I appreciate all contributions above. I have just applied the suggestions above to solve my challenge & it works fine. Keeping it simple I use the following:
<form id="newuser" action="newuser.php" onsubmit="return pswderr(this)">
For the button I have
<input id='submit' type="submit" value="Login" onClick="return pswderr();">
My script is:
<script>
function pswderr() {
var pswd1 = document.getElementById("newuserpswd").value;
var pswd2 = document.getElementById("rptpswd").value;
if (pswd1 !== pswd2) {
document.getElementById("alarm").innerHTML = "Password and password
verification do not match. Retry";
return false;
} else {document.getElementById("alarm").innerHTML = "";
return true;
}
}
</script>
use return on the onclick attribute in the form tag attribute onsubmit="return validateForm()" , if you return false in your validation function in javascript if the input is incorrect then you have to add return to your onclick attribute in order for it to execute .Hope it helped someone!
<script>
function validateForm(){
var validation = false;
var phonenumber = document.forms["enqueryForm"]["phonenumber"].value;
if(phonenumber != 11) {
alert("phonenumber is incorrect");
//e.preventDefault();
return false;
}
}
</script>
<form class="form-style-5" action="BookingForm.php" method="post" id="bookingForm" onsubmit="return validateForm()" name="enqueryForm">
<input type="tel" name="phonenumber" placeholder="your no.">
<input type="submit" name="submit" value="submit">
</form>
return is not going to stop the form from submit if its called in a subfunction e.g. compare(sDate, eDate)
so change your function to this
function dateCheck(e){
var start = document.getElementById('name3').value;
var end = document.getElementById('name4').value;
if(compare(start, end)) {
// no error submit i guess
// return true ?
} else {
// error with date compare
return false;
}
end.focus();
}
In my case i used pattern in input field and also gave maxlength.
What worked with me was, remove Length attribute from input field
you can achieve the same thing using jQuery Form Plugin.
$(document).ready(function() {
$('#your_form_id').ajaxForm( { beforeSubmit: dateCheck } );
});
- I hope this will help you : Just write this code on your Html/jsp page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
- **Don't forget to add this on your html page**
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
//option A
$("regF").submit(function(e) { //regF is form id
alert('submit intercepted');
e.preventDefault(e);
});
});
</script>
</html>
Please i just started learning javascript, In order to build my skill. I gave myself a javascript project to build an object validator.The first method i created is checkEmpty. This method check for empty field. But for reason unknow to me the method don't work.
This is the html form
<form name="myForm">
<input type="text" class="required email" name='fName'/>
<input type="text" class="required number" name="lName"/>
<input type="submit" value="submit" name="submit" id="submit"/>
</form>
This is the javascript that called the validator object
window.onload = function(){
var validate = new FormValidator('myForm');
var submit = document.getElementById('submit');
//this method won't work for internet explorer
submit.addEventListener('click',function(){return checkLogic();},false);
var checkLogic = function(){
validate.checkEmpty('fName');
};
}
This is the javascript object called Formvalidation
function FormValidator(myForm){
//check ur error in stack overflow;
this.myForm = document.myForm;
this.error = '';
if(typeof this.myForm === 'undefined'){
alert('u did not give the form name ');
return;
}
}
//this method will check wheather a field is empty or not
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
This method printout the error;
FormValidator.printError = function(oData){
alert(oData);
};
After formatting your code it got a lot easier to find out what went wrong. I assume you are trying to validate the input fields from your html code.
Your code is falling on its nose the first time in line 1 of the method checkEmpty():
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
In the first line you are hiding the methods argument oEmpty with the var oEmpty statement from line 1
There are several other issues like overusing methods and members. The following code is probably what you wanted:
1.) index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form name="myForm">
<input id="fName" name='fName' type="text"/>
<input id="lName" name="lName" type="text"/>
<input id="submit" name="submit" type="submit" value="submit"/>
</form>
<script src="main.js"></script>
</body>
</html>
2.) main.js
function InputFieldValidator(inputFieldName){
this.inputFieldName = inputFieldName;
this.inputField = document.getElementById(this.inputFieldName);
if(this.inputField === 'undefined'){
alert('No input field: ' + this.inputFieldName);
}
}
InputFieldValidator.prototype.validate = function(){
if(this.inputField.value === ''){
alert('Please enter valid text for input field: ' + this.inputFieldName);
}
};
window.onload = function(){
var fNameValidator = new InputFieldValidator('fName'),
lNameValidator = new InputFieldValidator('lName'),
submitButton = document.getElementById('submit');
submitButton.addEventListener('click', function (){
fNameValidator.validate();
lNameValidator.validate();
});
};
If you like you can wrap the input field validators from above easily in a form validator.
This is the right way to define functions this way:
var FormValidator = function(myForm){ /* function body */ };
FormValidator.prototype.checkEmpty = function(oEmpty){ /* function body */ };
Than, after instantiating the object, you can call FormValidator.checkEmpty(value) like you did.
Im getting a error in the Web Inspector as shown below:
TypeError: 'null' is not an object (evaluating 'myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}')
Here is my Code (HTML):
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<script src="js/script.js" type="text/javascript"></script>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
Here is the JS:
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
Any Idea why I am getting the error?
Put the code so it executes after the elements are defined, either with a DOM ready callback or place the source under the elements in the HTML.
document.getElementById() returns null if the element couldn't be found. Property assignment can only occur on objects. null is not an object (contrary to what typeof says).
Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML.
So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.
So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.
Then you can add an event listener for document load to execute the function.
That will give you something like:
<script>
function init() {
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
document.addEventListener('readystatechange', function() {
if (document.readyState === "complete") {
init();
}
});
</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/
Try loading your javascript after.
Try this:
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
<script src="js/script.js" type="text/javascript"></script>
I think the error because the elements are undefined ,so you need to add window.onload event which this event will defined your elements when the window is loaded.
window.addEventListener('load',Loaded,false);
function Loaded(){
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
I agree with alex about making sure the DOM is loaded. I also think that the submit button will trigger a refresh.
This is what I would do
<html>
<head>
<title>webpage</title>
</head>
<script type="text/javascript">
var myButton;
var myTextfield;
function setup() {
myButton = document.getElementById("myButton");
myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName("h2")[0].innerHTML = greeting;
}
</script>
<body onload="setup()">
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
</body>
</html>
have fun!