I'm trying to code a validation or registration form that requires a Name, 2 Matching Passwords, and an Email. As of right now I'm hung up on the alert that pops up if the Name Input (which I styled using a div) is empty. We're supposed to be using mostly If/Else functions.
Here is what I have so far.
<body>
<div id='register'><p>Register Here:</p></div>
<div id='background'>
<input type="text" placeholder="Name" id="A" ></input>
<input type="password" placeholder="Password" id="B"></input>
<input type="password" placeholder="Confirm Password" id="C"></input>
<input type="email" placeholder="Email" id="D"></input>
</div>
<input type="Submit" id="button"></input>
and
$(document).ready(function(){
var Name = $('A').val();
var Pass = $('B').val();
var Confirm_Pass = $('C').val();
var Email = $('D').val();
$('#button').click(function(){
if(!Name){
alert("Fill in all boxes");
}
else{
alert('valid');
}
});
});
What happening as of now is that I'll receive the alert "Fill in all boxes" even if the input is filled.
Here's a working example: http://jsfiddle.net/p6hYa/
There are few issues here noted in the comments below:
$(document).ready(function(){
//Selecting by ID is in the form $("#ID")
var Name = $('#A'); //You want to get the values AFTER submit is clicked, otherwise this will always be the initial empty value.
var Pass = $('#B');
var Confirm_Pass = $('#C');
var Email = $('#D');
$('#button').click(function(){
if(!Name.val()){ //Inside the click event you grab the value
alert("Fill in all boxes");
}
else{
alert('valid');
}
});
});
$('A')
Will search for
<A></A>
You are looking for
$("#A")
Related
I have written the below code to make a simple form for validation of form inputs through javascript. Here username and passwords are written in the JS code, but it still shows alert message of the else loop even if giving correct credentials on the form.
Please Help?
var user = document.getElementById('username')
var pass = document.getElementById('password')
function user1() {
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" Placeholder="enter username"><br>
<input type="password" name="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
There are a few errors here:
You need to get the values of your inputs
You want to get those values when the button is clicked. Your code is grabbing them only when the page loads. Move the variable assignment into your function
You didn't give the elements ID attributes
function user1() {
var user = document.getElementById('username').value
var pass = document.getElementById('password').value
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" id="username" Placeholder="enter username"><br>
<input type="password" name="password" id="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
Also note that a button's default type is submit which will submit your form and reload the page after the alert is shown when clicked, so you might want to change that to type="button" to prevent that.
I am validating a login form. My password field is working perfectly as I want but while validating USERNAME field I'm calling ajax for username validation i.e to check if username exists and after that if username field is empty calling a js function which shows a message but here I'm having a popup message but I wanted to display that message above the textbox. How can i do that?
Thanks in advance. :)
Add an error holder before the input box.
<span style="display:none;color:#E84344;" id='USERNAME_ERROR'> </span>
<input type="text" name="USERNAME" id="USERNAME" class="form-control input-lg" placeholder="Email or User Name" onchange="CheckLoginCustomer('loginform')"/>
Following Change you need to do in loginvalidation function
function loginvalidation(formname)
{
var form=document[formname];
var USERNAME= form.USERNAME.value;
var PASSWORD= form.PASSWORD.value;
var userNameFlag = form.userNameFlag.value;
if(USERNAME == '')
{
document.getElementById('USERNAME_ERROR').innerHTML = 'Please Enter Registered UserId';
document.getElementById('USERNAME_ERROR').style.display = 'block';
return false;
}
.....
.....
Whereever you dont want to show this error message do the following:
document.getElementById('USERNAME_ERROR').innerHTML = '';
document.getElementById('USERNAME_ERROR').style.display = 'none';
Do the same for others ..
i'm making a code for you please check below link:
https://jsfiddle.net/fatehjagdeo/9way7qc2/1/
or check my code below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<form>
<input type="text" id="username"><br>
<input type="password" id="password"><br>
<input type="button" value="submit" id="submit">
</form>
<script>
$(document).on('click','#submit',function(){
$('.error').remove();
var username=$('#username').val();
var password=$('#password').val();
var err=0;
if(username==""){
$('#username').before('<p class="error">Please enter username</p>');
err=1;
}
if(password==""){
$('#password').before('<p class="error">Please enter password</p>');
err=1;
}
if(err==0){
// send your ajax here
}
});
</script>
I'm attempting to send an error message when either the email field or the phone field of a form doesn't match the regex. The validation message shouldn't submit if either fields are filled in.
What happens right now when I go to submit the form with one of the fields filled in with the proper information the form gives me the error message and will not post the form. Once I enter the correct input into the other field it processes the form.
What I want it to do is to process the form if either the email field is filled out or the phone field is filled out with information that matches the regular expressions.
If neither of the forms are filled out correctly I want the form to throw the error message.
Here's the if statement I am working with so far.
<form id="contact_form" action="" method="POST">
<input type=hidden name="" value="">
<input type=hidden name="" value="">
<p class="errmsg" id="name_errormsg"></p>
<input id="name" maxlength="80" name="form_name" placeholder="Name" size="20" type="text" />
<input id="email" maxlength="80" name="email" placeholder="Email" size="20" type="text" />
<input id="phone" maxlength="40" name="phone" placeholder="Phone number" size="20" type="text" />
<textarea id="description" name="description" placeholder="How can we help you?"></textarea>
<input type="submit" name="submit" value="Send message">
</form>
$(document).ready(function() {
$overlay = $(".modal-overlay");
$modal = $(".modal-frame");
$modal.bind('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
if($modal.hasClass('state-leave')) {
$modal.removeClass('state-leave');
}
});
$('.form-close-button').on('click', function(){
$overlay.removeClass('state-show');
$modal.removeClass('state-appear').addClass('state-leave');
});
$('#contactformbtn').on('click', function(){
$overlay.addClass('state-show');
$modal.removeClass('state-leave').addClass('state-appear');
});
var formHandle = document.forms[0];
formHandle.onsubmit = processForm;
function processForm(){
var emailInput = document.getElementById('email');
var emailValue = emailInput.value;
var phoneInput = document.getElementById('phone');
var phoneValue = phoneInput.value;
var regexPhone = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/;
var regexEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if((!regexPhone.test(phoneValue)) ||(!regexEmail.test(emailValue))) {
nameErr = document.getElementById("name_errormsg");
nameErr.innerHTML = "Please enter your phone number or a valid email address.";
nameErr.style.color = "red";
return false;
}
}
});
If any of you could point out where I went wrong this that would be great!
Thank you for taking the time to read this.
Have a good day.
Based on your last comment (which should be in the question) your logic is wrong.
You're currently checking for failure of either field. If phone fails or email fails. If one field isn't filled in it'll fail because you don't allow blank.
You want to test for failure of both fields (with a caveat):
if (!regexPhone.test(phoneValue) && !regexEmail.test(emailValue)) {
....
Or you can change your regex.
The caveat is that say a user enters in a valid phone, but an invalid email: what should happen in that case? Should validation pass or fail?
I have an HTML form that I would like to make interact with some JavaScript:
...
<form name="signup">
<label id="email" for="email" placeholder="Enter your email...">Email: </label>
<input type="email" name="email" id="email" />
<br />
<input type="submit" name="submit" id="submit" value="Signup" onclick="signup()"/>
</form>
...
I have some JavaScript that I want to take the entered email address and store it in an array (it is currently inline with my HTML hence the script tags):
<script type="text/javascript" charset="utf-8">
var emailArray = [];
function signup(){
var email = document.signup.email.value;
emailArray.push(email);
alert('You have now stored your email address');
window.open('http://google.com');
console.log(emailArray[0]);
}
</script>
I was hoping that this simple script would store the email in emailArray but the console remains empty throughout the execution.
What is wrong with this code?
You have two problems.
Your form is named signup and your global function is named signup. The function is overwritten by a reference to the HTML Form Element Node.
Your submit button will submit the form, causing the browser to leave the page as soon as the JS has finished (discarding all the stored data and probably erasing the console log)
Rename the function and add return false; to the end of your event handler function (the code in the onclick attribute.
Please rename your function name (signup) or Form Name (signup),
because when you are try to access document.signup......
It'll make a type error like, object is not a function
Try below Code,
<script type="text/javascript">
var emailArray = [];
function signup() {
var theForm = document.forms['signupForm'];
if (!theForm) {
theForm = document.signupForm;
}
var email = theForm.email.value;
emailArray.push(email);
console.log(emailArray[0]);
}
</script>
<form name="signupForm">
<label id="email" for="email" placeholder="Enter your email...">Email: </label>
<input type="email" name="email" id="email" />
<br />
<input type="button" name="submit" id="submit" value="Signup" onclick="signup(); return false;"/>
</form>
The problem that is given is that the form name is "signup" and the function is "signup()", then the function is never executed (this is better explained in this answer). If you change your form name or your function name everything should work as expected.
try this code :
<form name="test">
<label id="email" for="email" placeholder="Enter your email...">Email: </label>
<input type="text" name="email" id="email" onBlur=/>
<br />
<input type="button" name="submit" id="submit" value="Signup" onclick="signup()"/>
</form>
<script type="text/javascript" charset="utf-8">
var emailArray = [];
function signup(){
var email = document.getElementById('email').value;
emailArray.push(email);
alert('You have now stored your email address');
window.open('http://google.com');
console.log(emailArray[0]);
return false;
}
</script>
As suggested in the comments, just change your email variable to:
var email = document.getElementById('email').value;
then just push it to your emailArray
EDIT
You'll need to rename the ID of your label. The reason it's currently not working is because the value being returned is that of the first element with the id of email (which is your label, and undefined).
Here's a Fiddle
I would propose two improvements to your code:
Put your javascript right after the <form> element in order to be sure that dom element exist in the document
Attach click handler using addEventListener method. Read more here.
Email:
var emailArray = []; function signup(){ var email = document.getElementById('email').value; emailArray.push(email); alert('You have now stored your email address'); window.open('http://google.com'); console.log(emailArray[0]); return false; } document.getElementById("submit").addEventHandler('click', signup, false);
I'm trying to validate a form, but doesn't work :\ , When I submit the form goes to mail.php even if the required fields are missing, but I set onsubmit to validate() so it should check, but doesn't work. What's the problem with my code? I can't find it.
HTML:
<form action="mail.php" onsubmit="return validate()" method="post" class="contact-form" id="contactForm">
<div id="errors"></div>
<label for="author">Name:</label><br/><br/>
<input type="text" name="author" id="message" /><br/><br/>
<label for="author">Message:</label><br/><br/>
<textarea name="message" id="message"></textarea><br/><br/>
<input type="submit" class="button" value="Send Message"/>
</form>
Javascript:
<script type="text/javascript">
function error(message){
return "<p class=\"error\">"+message+"</p>";
}
function validate(){
var form = document.getElementById("contactForm");
var author = document.getElementById("author");
var message = document.getElementById("messsage");
var errors = document.getElementById("errors");
alert(author.value);
if(message.value == '' || author.value == ''){
errors.innerHTML = error("Please fill in all fields.");
return false;
} else {
return true;
}
}
</script>
id=author on your first input element.
Also check out jQuery it will save you time in the long run
You have two elements with the id message and none with author.
The Markup Validator would have picked this up for you.
var message = document.getElementById("messsage");
message has an extra "s".
<input type="text" name="author" id="message" />
You need to change "message" to "author"
This is wrong:
<input type="text" name="author" id="message" />
Need to set name and id to the same values (you're using id="message" for the next field, so there's a clash.
Also both your label tags have for="author"; the second one is wrong.
I guess your problem here is too much copy+paste. ;)