The below form is being submitted even when its txt_approver is empty.
But it works well in firefox/chrome?
I get no error, what could be the issue?
<script>
function validateForm() {
var x = document.forms["warningnotice"]["txt_approver"].value;
alert(x);
if (x == null || x == "") {
alert("Please enter a name to send a email to ");
return false;
}
}
</script>
<form method="post" action="travel.cfm" id="commentForm" name="warningnotice" onsubmit=" return validateForm()">
<td ><input type="text" name="txt_approver" class="get_empl" required data-error="#errNm35"></td>
<input type="submit" name="Submit" value="Submit" >
</form>
You are using the name attribute to locate the form and the textbox in JavaScript. This is not what the name attribute is for. The id attribute is for this.
Instead of:
document.forms["warningnotice"]
and
<input type="text" name="txt_approver" ...
Those lines should be:
document.forms["commentForm"]
and
<input type="text" name="txt_approver" id="txt_approver"...
And, instead of document.forms, use:
var form = document.getElementById("commentForm");
var tb = document.getElementById("txt_approver");
Also, instead of:
if (x == null || x == "")
You can just use:
if (!String.trim(x))
Because an empty textbox will produce an empty string "" and an empty string, converted to a boolean (which an if statement looks for) will be false, but a populated one, will convert to true.
Lastly, you probably don't want to have your submit button have a name attribute at all because when the form is submitted, the value of the submit button will be submitted along with the other form elements, which probably is not what you want.
The following JS Fiddle shows the code that is working for me in IE 11: https://jsfiddle.net/x0rbnL5s/
Related
Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation
I want to create a form and want to validate user input, if user fill both text box i want to show an alert box, also if user fill one and left empty another one i want to show an alert box to let them know that they are missing one box. How i can do it with JavaScript, please help.
I want two text box, if user fill both text box and click enter i want to show an alert box telling them "Correct", if user fill one and left another empty i want to show an alert box telling them that it is "Incorrect".
How i can do it, help.
<form action="" method="post">
<input type="text" name="text1" placeholder="Text 1">
</br>
<input type="text" name="text2" placeholder="Text 2">
</br>
<input type="submit" value="Enter">
</form>
What kind of validation are you interested in ?
You can do everything with javascript my friend:).
This is pure javascript. To make it simple, I kept the html and js in one file. I also added a name to a form as you see below, in case you would have multiple forms.
<html>
<body>
<form name="LovelyForm" action="" method="post">
<input type="text" name="text1" placeholder="Text 1"> </br>
<input type="text" name="text2" placeholder="Text 2"> </br>
<input type="submit" onclick="validateForm()" value="Enter">
</form>
<script type="text/javascript">
function validateForm() {
var x = document.forms["LovelyForm"]["text1"].value;
var y = document.forms["LovelyForm"]["text2"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Fill me in");
return false;
}else{
alert("Good");
return true;
}
}
</script>
</body>
</html>
Validation with javascript is the most flexible way and works with all browsers, if you learn JQuery you will be able to improve the user experience limit less.
If you don't want to javascript then use the new improved input validation options with Html 5, they will work with most browsers and not break the ones without Html5 support.
Here: Best practice as I see it :)
Only validate the most necessary on client side.
Avoid compulsory input unless they realy are.
Don't refuse space, hyphens, commas, dots and so on if you absolutely don't have to. People like to cut and paste. You can always clean on server side.
Don't limit input length/size if you don't have to. Again people like to cut and paste and many times the input is to long just because it contains blank spaces.
Most important of all. You must always validate on server side, to make sure your data won't get corrupted. Client validation is only to improve the users experience and not a substitute.
Here's a JSFiddle that should work with IE < 9: http://jsfiddle.net/ayr7yov7/1/
form.elements['one'].value may cause issues if the inputs are not of type text.
The code:
<script>
function trim(str) {
if(!str) return '';
return str.replace(/\s{2,}/g, '');
}
function valid(form) {
var v1 = trim(form.elements['one'].value),
v2 = trim(form.elements['two'].value);
if (v1 === '') {
alert('one');
return false;
}
if (v2 === '') {
alert('two');
return false;
}
alert('full!')
return true;
}
</script>
<form action="/echo/json/" onsubmit="return valid(this)">
<input name="one" type="text" />
<input name="two" type="text" />
<input type="submit" />
</form>
First step is to give JavaScript an easy way to reference the element in the DOM. Generally, the easiest way is to give each element you need to reference a unique ID.
<input id="num1" />
<input id="num2" />
Then, JavaScript can access the inputs with the getElementById() method of the document object (the "D" from DOM).
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
Now, i1 and i2 contain a reference to their respective input objects (the "O" from DOM). Every form element object has a value attribute that contains the current value of it's input.
var val1 = i1.value;
var val2 = i2.value;
Now var1 and var2 contain the value of the input. All you have to do is check and see if they both have a value that isn't empty.
if(
// if the first value does not equal an empty string ""..
val1 != ""
// and the second value does not equal an empty string ""..
&& val1 != ""
)
// then alert 'correct'
alert("correct");
// or else, alert 'incorrect'
else alert('incorrect');
Now you can throw it in a function and make it run when the form is submitted by attaching it to an event handler. When you're just starting it's easiest to use an onsubmit attribute, which takes the name of a function and calls that function when the form is submitted.
<form action="#" onsubmit="validate()">
<input id="num1" />
<input id="num2" />
<input type="submit" />
</form>
<script>
function validate(){
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
var val1 = i1.value;
var val2 = i2.value;
if(val1 != "" && val2 != "") alert("correct");
else alert("incorrect");
}
</script>
My purpose: If the user field and password field are blank, I want to stop form submitting.
This is my Code that I am trying:
<!DOCTYPE html>
<html>
<head>
<script>
function doit() {
var usr = document.getElementById('ur').value;
var psw = document.getElementById('pw').value;
if ((usr.trim() == '') && (psw.trim() == '')) {
alert("cannot Submit form");
return false;
}
}
</script>
</head>
<body>
<form action="post.php" method="post" onsubmit="doit()">
User:
<input type="text" id="ur" name="user">
<br>
<br> Pass:
<input type="password" id="pw" name="pass">
<br>
<br>
<button>Submit</button>
</form>
</body>
</html>
I am learning JavaScript. Will be helpful if you correct the code with a little explanation why it is not working.
return false is working fine, the way you are calling that function is wrong.
<form action="post.php" method="post" onsubmit="doit()">
Just calls it, doesn't do anything with the return value
<form action="post.php" method="post" onsubmit="return doit()">
^
Will stop the form post on a false returned value.
Read this note on MSDN although it is not IE specific
You can override this event by returning false in the event handler. Use this capability to validate data on the client side to prevent invalid data from being submitted to the server. If the event handler is called by the onsubmit attribute of the form object, the code must explicitly request the return value using the return function, and the event handler must provide an explicit return value for each possible code path in the event handler function.
Now onto another important point.
Your if condition will only stop form submission when both the fields are blank, whereas it should do that even if any one of those two fields is blank. That && (AND) should be an || (OR), and at the end of your functions if nothing returned false, return true then.
onsubmit event accepts boolean values, since you are not returning anything so it assumes true by default. You need to add return in this event explicitly like mentioned below:
change
onsubmit="doit()">
to
onsubmit="return doit()">
Using addEventListener on submit with preventDefault()
document.form1.addEventListener( "submit", function(event) {
var user = this.querySelector("input[name=user]").value; // this = object of form1
var pass = this.querySelector("input[name=pass]").value;
if ( (user.trim() == "") || (pass.trim() == "") ) {
alert("cannot Submit form");
event.preventDefault();
} else {
alert("submit");
}
} );
<form action="" method="post" name="form1" >
Username: <input type="text" name="user" /><br><br>
Password: <input type="password" name="pass" /><br><hr>
<input type="submit" value="Submit" />
</form>
codepen
repl.it
I have a form, and I've written a validation script for it, however, it's not working 100%. It outputs errors fine, but the submit button will submit the form, even if it has outputted the alert boxes. Anyone have any idea why?
Apparently not all the code pasted. I would just use the Required parameter, but I need JS validation as it is an assignment. Also, UL is defined before this part of code, as there is a list before this.
HTML:
<div class = "form">
<form name = "contactForm" onsubmit="validateForm()" action = "form.php">
<li><label>First name: </label><input type = "text" name = "fname" autofocus></li><br>
<li><label>Last Name: </label><input type = "text" name = "lname"></li><br>
<li><label>Email: </label><input type = "text" name = "email"> <button onclick = "validateEmail();return false">Check if email is valid</button> </li><br>
<li><label>Message: </label> <br>
<textarea rows = "10" cols = "50" name = "message"></textarea></li>
<li> <input type = "submit"> </li>
</form>
JavaScript:
function validateForm()
{
var x=document.forms["contactForm"]["fname"].value; //Gets the form and field name from the HTML
if (x==null || x=="") //If the field "fname" contains null, or nothing, then output an alert telling the user to input something into the field. Same goes for the rest of the code.
{
alert("First name must be filled out");
return false;
}
var x=document.forms["contactForm"]["lname"].value;
if (x==null || x=="")
{
alert("Last name must be filled out");
return false;
}
var x=document.forms["contactForm"]["email"].value;
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(x) == false)
{
alert("Please enter a valid Email");
return false;
}
if (x==null || x=="")
{
alert("Email must be filled out");
return false;
}
var x=document.forms["contactForm"]["message"].value;
if (x==null || x=="")
{
alert("Message must be filled out");
return false;
}
}
You have to trigger event on time of submit. Like this way:
<form onsubmit="validateForm()">
How are you attaching the event listener? I’d wager it’s with:
<form … onsubmit="validateForm()">
You’d need return validateForm(). But wait! Don’t add that.
Your script does not check for valid e-mail addresses correctly. It only checks one error at once. It will annoy users. Use HTML5 validation and back it up with PHP.
By applying type="email", you don’t need a button at all, and mobile users will see an e-mail specific keyboard if available. The browser will validate it, given support.
<input type="email" name="email">
Required fields should use the required attribute.
<input type="text" name="fname" autofocus required>
⋮
<input type="text" name="lname" required>
Your labels aren’t correct either; they should surround the element they’re related to, or provide a for attribute matching the element’s id.
You should also validate your HTML. And not put <br>s between <li>s.
Finally, as general [client-side] JavaScript tips:
You don’t have to check the value of a text field for null.
Write !x instead of x == false.
You can also use JQuery to do something like this:
$( "#formId" ).submit(function( event ) {
if($("#nameInput").val() == "")
event.preventDefault();
});
So basically, if nameInput's equals to empty the submit action will be canceled
Take a look at here if you want: https://api.jquery.com/submit/
Good luck
Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();