JavaScript Alert message not working - javascript

Below is the code that I have put together to validate 5 fields, of a form that has like 9 fields, that are to be required. I created the variables and placed them into an array. From there I have a function that loops through this array to see pop up an alert if that field is left blank.
The problem that I am coming across is that the alerts are not popping up when the button is clicked.
var uName=document.getElementByName('userName');
var pword=document.gelElementByName('password');
var verify=document.getElementByName('passwordVerify');
var fName=document.getElementByName('firstName');
var lName=document.getElementByName('lastName');
var field=[uName,pword,verify,fName,lName];
function validateForm(form) {
for(var i = 0; i < form.field.length; i++){
if(form.field[i].value.length == 0){
alert(form.field[i].name+' is required. Please populate');
form.field[i].focus();
return false;
}
} return true;
}
Not sure what I did wrong or what is causing the error. Any assistance is greatly appreciated.

function validateForm() {
var uName = document.getElementById('userName');
var pword = document.getElementById('password');
var verify = document.getElementById('passwordVerify');
var fName = document.getElementById('firstName');
var lName = document.getElementById('lastName');
var field = [uName, pword, verify, fName, lName];
for (var i = 0; i < field.length; i++) {
if (!field[i].value) {
alert(field[i].name + ' is required. Please populate');
field[i].focus();
return false;
}
}
return true;
}
<form>
<input type="text" id="userName" name="userName" /><br/>
<input type="text" id="password" name="password" /><br/>
<input type="text" id="passwordVerify" name="passwordVerify" /><br/>
<input type="text" id="firstName" name="firstName" /><br/>
<input type="text" id="lastName" name="lastName" /><br/>
<button onclick="validateForm();">Submit</button>
</form>
Now, here are the changes I made:
I changed getElementByName to getElementById throughout your code, for simplicity;
I removed the function's parameter, and changed form.field to field because... Well, the first one was just wrong.
I also changed the iterating test to !field[i].value, which is equivalent to testing if the value has a length, but seemed more appropriate to me.
That's about all I did, along with adding ID's to the form's elements.
P.S: That is my first detailed answer here, feedback would be greatly appreciated! :)

Related

Compare input text with person name belongs to only one input number id

Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}

Getting text from input form returns empty string, but console.log shows displays text

I know this is a commonly posted question so I apologize, but I've tried javascript, jQUERY, parts of this,several versions from previous work that DO work, .value, .textContent, .innerHTML, getAttribute('value'), document.getElementById and just everything else I could think of.
I console.log(user_name.value) and get the value I want, but when I console.log(name) or try to use user_name.value it's just an empty string. I'm new to development and got all the rest of the code working, everything else is hanging on this simple part and I can't solve it yet. Any help would be so appreciated.
HTML:
<form>
<input id="user_name" type="text" placeholder="Your Name" />
<input id="user_email" type="text" placeholder="Your E-mail" />
</form>
JavaScript:
var name;
var email;
function reserveSeat(name, seatNumber, email) {
var name = $('#user_name').getAttribute('value');
var email = $('#user_email').getAttribute('value');
var seatNumber = seatNumbers;
reservedSeats.push (new CustomerReservation (name, seatNumber, email));
console.log(name)
console.log(email)
};
$('.submitBtn').on('click', reserveSeat(name, seatNumber, email));
You tried all but the right one: val()
name = $('#user_name').val();
email = $('#user_email').val();
Note: if submitBtn is a type submit don't forget to prevent the default event,
$('.submitBtn').on('click', function(e){
e.preventDefault();
name = $('#user_name').val();
email = $('#user_email').val();
reservedSeats.push (new CustomerReservation (name, seatNumber, email));
console.log(name)
console.log(email)
});
Note2: if your form is dynamically added don't forget to delegate your event
there is no attribute called value in the input box and you are using jquery with javascript functions using ".val()" is the right option
Try this,
<form>
<input id="user_name" type="text" placeholder="Your Name" />
<input id="user_email" type="text" placeholder="Your E-mail" />
<input id="submitBtn" type="submit" class="submitBtn"/>
</form>
$(document).on('click','.submitBtn',function(){
var name = $('#user_name').val();
var email = $('#user_email').val();
console.log(name)
console.log(email)
});
please review this one
/*need gobal variable or not?? if not I will just remove it
var name;
var email; */
function reserveSeat(seatNumbers) {
/*for savety*/
seatNumber = Number(seatNumbers) || 5;
/* change getAttribute(value) to val()*/
var name = $('#user_name').val(),
email = $('#user_email').val();
reservedSeats.push(new CustomerReservation(name, seatNumber, email));
console.log(name);
console.log(email);
};
$('.submitBtn').on('click', reserveSeat(seatNumber));

Input type=password value returning empty unless i use a breakpoint in the chrome console

I'm trying to get the value of a password input box on window.onload however it keeps returning an empty string. If I set a break point and step through my code then it returns the correct string. And if i set a breakpoint anywhere before it and then just continue running the code it will also work. But running it without a break point somewhere stopping the code at some point or even using the longest setTimeout() doesnt seem to work.
A little background: im writing a solution to rid my design of the chrome autocomplete yellow background. I found a great solution that works but it removes the password value Solution Link. So i decided to first get the password value and then reset it once everything finishes. Heres my code:
window.onload = function() {
setTimeout(function() {
var documentForms = document.forms;
//First cycle through all the forms
for (var i = 0; i < documentForms.length; i++) {
var password = null;
// Now find the password and store its value
for (var k = 0; k < documentForms[i].elements.length; k++) {
var passwordInput = documentForms[i].elements[k];
if (passwordInput.type == "password") {
password = passwordInput.value; //This keeps returning ""
}
}
// Now using this solution remove the autocomplete yellow:
for (var j = 0; j < documentForms[i].elements.length; j++) {
var input = documentForms[i].elements[j];
if (input.type == "text" || input.type == "password" || input.type == null) {
var text = input.value;
input.focus();
var event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, window, 'a');
input.dispatchEvent(event);
input.value = text;
input.blur();
}
// Now that it has removed the password, if this is the password input, reset its value correctly
if (input.type == "password") {
input.value = password;
input.blur();
}
}
}
}, 300);
};
<form method="post" class="login">
<input type="text" class="input-text" name="username" id="username" value="" placeholder="Email Address" />
<input class="input-text" type="password" name="password" id="password" placeholder="Password" />
<input type="submit" class="button" name="login" value="Start" />
Forgotten password?
</form>
Chrome pretends it does not have a value for the field as a security measure. There's no way to hack around that.
You can change the styling as per answers to this question: Google Chrome form autofill and its yellow background
Try this:
var getPasswordValue = function getPasswordValue(inputEl){
inputEl.type = "text";
var value = inputEl.value;
inputEl.type = "password";
return value;
};

Why is return false not keeping my form from submitting?

http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.

Form validation !='' in if statement?

Can anyone tell me whats wrong with this code, im validating a form making sure all the fields have text in them before anyone can submit. everything works until i put in the !='' var. I am sure the id's are correct
<script src="jquery.js" type="text/javascript" language="javascript"></script>
<script language="javascript">
$(document).ready(function() {
// declare the flags outside the other functions
var username_ready = false;
var email_ready = false;
function checkSubmitStatus() {
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
if (username_ready && email_ready && emailvalue!='' && usernamevalue!='' && firstvalue!='' && lastvalue!='' && passwordvalue!=''){
$("#register").prop('disabled',false);
}
else {$("#register").prop('disabled',true);}
}
and here is my form code so you can see if thats the issue...
<p>First Name: <input id="first" type="text" name="name" maxlength="100"> </p>
<p>Last Name: <input id="last" type="text" name="name" maxlength="100"> </p>
<p> Email: <input type="text" name="email" id="email" maxlength="100" />
<span id="box" style="display:none"></span></p>
User Name : <input name="username" type="text" id="username" value="" maxlength="15" />
<span id="msgbox" style="display:none"></span>
<p> Password: <input id="password" type="password" name="password"> </p>
You spelt your variable name firstvalue incorrectly:
firstvale!=''
Edit
Move these 5 lines:
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
From where they are to right under function checkSubmitStatus(){ and above your big if statement.
Where they are now, they are only assigned once, to the value of the form when the page first loads which I'm assuming at least one of them is empty.
You need to move those lines into your checkSubmitStatus() function so that they get updated whenever the function is called. The final result should look like:
var username_ready = false;
var email_ready = false;
function checkSubmitStatus() {
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
if (username_ready && email_ready &&
emailvalue!='' && usernamevalue!='' &&
firstvalue!='' && lastvalue!='' && passwordvalue!=''){
$("#register").prop('disabled',false);
} else {
$("#register").prop('disabled',true);
}
}
Judging from your code, I get the feeling that it's copy-pasted together from different parts of your code. What might be happening is that emailvalue, usernamevalue etc are really out of scope at the time the checkSubmitStatus is called. I might also be wrong, but it's hard to tell more based on the provided code, since it seems to be alright.
You could do alert(emailvalue); before the if statement to see if you get undefined or some value. If it's undefined, you probably have a scope issue.
From the above code it also seems that you assign those variables values, before anything is really entered or the form is submitted.

Categories

Resources