Javascript - Script working only for one element - javascript

I have to forms on my webpage, one with name="login" and the other one with name="register" (code below). I use javascript for alerts if the input fields are empty on submitting.
It worked well when I only had one form on the webpage, but the problem starts when I add the other form. It works fine for the first form (login) but when I fill in and submit the second one, it alerts that the fields are empty. (Supposedly, because the login fields are empty).
What's causing this and how do I fix this?
HTML
<form method="post" action="" name="login" onSubmit="return valid();">
<label for="username">Username:</label><br>
<input type="text" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" name="password"><br>
<button type="submit" name="signin">Log inn</button>
</form>
<form method="post" action="index.php" name="register" onSubmit="return valid();">
<label for="username">Username:</label><br>
<input type="text" name="username"><br>
<label for="email">E-mail adress:</label><br>
<input type="text" name="email"><br>
<label for="password">Password:</label><br>
<input type="password" name="password"><br>
<button type="submit" name="signup">Registrer deg</button>
</form>
Script
<script type="text/javascript">
function valid()
{
if(document.login.username.value == "")
{
alert ("Please enter your username.")
document.login.username.focus();
return false;
}
if(document.login.password.value == "")
{
alert ("Please enter your password.")
document.login.password.focus();
return false;
}
}
</script>
<script type="text/javascript">
function valid()
{
if(document.register.username.value == "")
{
alert ("Please enter your username.")
document.register.username.focus();
return false;
}
if(document.register.email.value == "")
{
alert ("Please enter your e-mail adress.")
document.register.email.focus();
return false;
}
if(document.register.password.value == "")
{
alert ("Please enter your password.")
document.register.password.focus();
return false;
}
}
</script>

You are defining two separate functions with the same name, they are overwriting each other. Make two separate functions, validateLogin and validateRegister
<form method="post" action="" name="login" onSubmit="return validateLogin();"> ...
<form method="post" action="" name="login" onSubmit="return validateRegister();">
A slight improvement to your code is for you to pass the form into the handler, so it makes your code shorter and uses fewer globals
<form method="post" action="" name="login" onSubmit="return validateLogin(this);"> ..
function validateLogin(form)
{
if(form.username.value == "")
{
alert ("Please enter your username.")
form.username.focus();
return false;
}
if(form.password.value == "")
{
alert ("Please enter your password.")
form.password.focus();
return false;
}
}
And even better, hookup your handlers through JS instead of HTML
//After the HTML is loaded, and give your form an ID
document.getElementById('loginForm').addEventListener('submit', function(e){
// In IE, the event is global
e = e || window.event;
// "this" points to the form
if(this.username.value == "") {
alert ("Please enter your username.")
this.username.focus();
return false; // or e.preventDefault();
}
if(this.password.value == "") {
alert ("Please enter your password.")
this.password.focus();
return false; // or e.preventDefault();
}
});
And last but not least, you can abstract the work of checking for empty values so your two functions aren't doing the same work.
function createValidator(formId, validations) {
var form = document.getElementById(formId);
form.addEventListener('submit', function(e){
e = e || window.event;
for (var i=0; i < validations.length; i++) {
var elementName = validations[i].elName;
var errorMessage = validations[i].error;
if (form[elementName].value === "") {
alert(errorMessage);
return false; // or e.preventDefault()
}
}
});
}
// And set up both your handlers, remember to give your forms and ID
createValidator('formLogin', [{
elName: 'username',
error: 'Please enter your username'
}, {
elName: 'password',
error: 'Please enter your Password'
}]);
createValidator('formRegister', [{
elName: 'username',
error: 'Please enter your username'
},{
elName: 'email',
error: 'Please enter your email address'
},{
elName: 'password',
error: 'Please enter your Password'
}]);

Related

JS Function is invoked but no result

When I invoke the function it is getting invoked but it flashes the result. Could please tell me what is the mistake I did?
Below is the HTML Code I used:
I have replaced the input type as a button but still, error not fixed.
function reg() {
//Name Field
var f = document.forms["registration"]["fullname"].value;
if (f == "") {
alert("Enter the name");
return false;
} else if (!f.match(/^.[a-zA-Z]+$/))
{
alert("Enter only alphabets");
return false;
}
document.getElementById('details').innerHTML = "Hi" + registration.fullname.value;
}
<form name="registration" onsubmit="return reg()">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
Here is what I believe you want to do.
Note it is better to add an event handler in the script rather than having an inline handler, but for now I pass the form itself in the function
function reg(form) {
//Name Field
var f = form.fullname.value;
if (f == "") {
alert("Enter the name");
return false;
}
// no need for else when you return
if (!f.match(/^[\. a-zA-Z]+$/)) { // I personally have a space in my full name
alert("Enter only alphabets and space");
return false;
}
document.getElementById('details').innerHTML = "Hi " + f;
// change to true if you want to submit the form but you will then not be able to see the HI
return false;
}
<form name="registration" onsubmit="return reg(this)">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
<span id="details"></span>

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

JavaScript Validation error message is not disappearing after I click submit

The code below validates a form with two fields. When I click the submit button without any data the error messages would show which is working fine but if I input data after and click submit button the error message doesn't disappear.
<script>
function validateForm() {
var valid = true;
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
</script>
</head>
<body>
<form action="#" method="post" name="myForm" onsubmit=" return validateForm()">
<div>
<label for="myActivityName">*Activity Name:</label>
<input type="text" name="activityName" value="" placeholder="Enter Activity Name" />
<p id="activityName"></p>
</div><br>
<div>
<label for="reporter">*Reporter:</label>
<input type="text" name="reporter" value="" placeholder="Enter Reporter " />
<p id="reporter"></p>
</div><br>
<input type="submit" value="Submit" >
</form>
</body>
The other answer is right, but here is some code to back it up with. Notice that the innerHTML of both activityName and reporter get (re)set back to empty before the validation occurs:
function validateForm() {
var valid = true;
document.getElementById("activityName").innerHTML = "";
document.getElementById("reporter").innerHTML = "";
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
Your problem is you never "unvalidate" the form a.k.a. remove the previous validation errors. Before you return from validation, if there were no errors, just revert your validation checks. This will ensure it will "clean" your interface if nothing is wrong.

form is submitting instead return false javascript

I am trying to test my form for validation. I don't have an .asp or .php file so I was informed I could use action="". My code doesn't seem to function right.On codepen it shows as values being posted. Jsfiddle gives me an error thats a paragraph long. In browser the page just seems to refresh. I have no alerts showing for anything....
what am I doing wrong here?
HTML:
<form name="name_form" action="" onsubmit="ValidateFormJS()" method="post">
First Name:
<input type="text" name="first_name">
<br> Last Name:
<input type="text" name="last_name">
<br>
<input type="submit" value="Submit">
</form>
Javascript:
function ValidateFormJS() {
var first = document.forms["name_form"]["first_name"].value;
var last = document.form["name_form"]["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
} else {
alert("Form Submitted.");
return true;
}
}
The returned values from the function are never used.
You forgot return before the function call on onsubmit event.
onsubmit="return ValidateFormJS()"
Another problem is that you're using document.form to get the value of last name. It should be document.forms.
The last else can be removed.
Demo
var form = document.forms["name_form"];
function ValidateFormJS() {
var first = form["first_name"].value,
last = form["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
}
}
<form name="name_form" action="" onsubmit="return ValidateFormJS()" method="post">
First Name:
<input type="text" name="first_name">
<br>Last Name:
<input type="text" name="last_name">
<br>
<input type="submit" value="Submit">
</form>
try this
in view
<form name="name_form" action="" onsubmit="return ValidateFormJS();" method="post">
in js code
function ValidateFormJS() {
var first = document.forms["name_form"]["first_name"].value;
var last = document.form["name_form"]["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
}
alert("Form Submitted.");
return true;
}

How to get `form.field.value` in jQuery?

in javascript i can validate a form on submit like below:-
<form action="" method="post" onsubmit="return validate(this)">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
function validate(loginForm){
if(loginForm.uName.value == ''){
alert('Please Enter Username');
loginForm.uName.focus();
}else if(loginForm.passKey.value == ''){
alert('Please Enter Password');
loginForm.passKey.focus();
}else {
return true;
}
}
</script>
I tried with below jQuery Code
<form action="" method="post">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
$('form').submit(function(loginForm){
if(loginForm.uName.val() == ''){
alert('Please enter username');
loginForm.uName.focus();
}else if(loginForm.passKey.val() == ''){
alert('Please enter username');
loginForm.passKey.focus();
}else {
return true;
}
return false;
});
</script>
But not works me... please help me...!
like this?
$('#submit').click(function(){
if( $('#uName').val() == ''){
alert('empty');
}
});
http://jsfiddle.net/TTmYk/
the submit form has a typo in my fiddle u might need to fix that
See the Form Fields jQuery Plugin:
https://github.com/webarthur/jquery-fields
You can use the plugin as follows:
var form = $('form#id_form').fields();
form.name.val('Arthur');
form.age.hide();
form.description.css('height', 200);
Or this way:
var form = $('form#id_form').fieldValues();
form.name('Arthur');
form.age(29);
form.description('Web developer.');
var name = form.name();
The argument in the submit callback function is not the element instead it is the event. So inside the callback this represents the form element so you could just do this.uName.value and you can avoid the use of id as well.
So
$('form').submit(function(e){
if(this.uName.value == ''){
alert('Please enter username');
this.uName.focus();
}else if(this.passKey.value == ''){
alert('Please enter username');
this.passKey.focus();
}else {
return true;
}
return false;
});
Fiddle
Plus val() is jquery method, and in plain javascript you would use value and in this case that should be sufficient enough.
This will help you:
jQuery(function($) {
var $username = $('#uName'),
$password = $('#passKey');
$('form').submit(function() {
if ($username.val() == '') {
alert('Please enter username');
$username.focus();
} else if($password.val() == '') {
alert('Please enter username');
$password.focus();
} else {
return true;
}
return false;
});
});
Some points you need to keep in mind:
If you will work with the DOM you should wrap your code inside a jQuery(function() { ... }); block.
If you want to access a DOM element with jQuery you need to select it before using $(...).

Categories

Resources