Simple HTML form with javascript function - javascript

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);

Related

how to validate a field twice in form without alert message/popup? sorry if repeated just provide me link

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>

HTML5 validation executes before custom validation

I have a form which asks user to give some input values. For some initial inputs i am doing custom validation using javascript. At the end of form one field is validated using "html required attribute". But when user clicks on submit button, input box which have required attribute shows message first instead of giving chance to previous ones i.e. not following order of error display. Below i added code and image , instead of showing that name is empty it directly jumps to location input box. This just confuses the end user. Why this problem occurs and how to resolve it?
<html>
<head>
<script>
function validate(){
var name = document.forms['something']['name'].value.replace(/ /g,"");
if(name.length<6){
document.getElementById('message').innerHTML="Enter correct name";
return false;
}
}
</script>
</head>
<body>
<form name="something" action="somewhere" method="post" onsubmit="return validate()">
<div id="message"></div>
Enter Name : <input type="text" name="name" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
</body>
</html>
This is probably just the HTML5 form validation triggered because of the required attribute in the location input.
So one option is to also set the required attribute on the name. And or disable the HTML5 validation with a novalidate attribute. See here for more information: https://stackoverflow.com/a/3094185/2008111
Update
So the simpler way is to add the required attribute also on the name. Just in case someone submits the form before he/she entered anything. Cause HTML5 validation will be triggered before anything else. The other way around this is to remove the required attribute everywhere. So something like this. Now the javascript validation will be triggered as soon as the name input looses focus say onblur.
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
var messageElement = document.getElementById('message');
var string = nameElement.value.replace(/ /g,"");
if(string.length<6){
messageElement.innerHTML="Enter correct name";
} else {
messageElement.innerHTML="";
}
};
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
Now the above works fine I guess. But imagine you might need that function on multiple places which is kind of the same except of the element to observe and the error message. Of course there can be more like where to display the message etc. This is just to give you an idea how you could set up for more scenarios using the same function:
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
validate(nameElement, "Enter correct name");
};
function validate(element, errorMessage) {
var messageElement = document.getElementById('message');
var string = element.value.replace(/ /g,"");
if(string.length < 6){
messageElement.innerHTML= errorMessage;
} else {
messageElement.innerHTML="";
}
}
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>

What is wrong whit this jQuery submit function?

This code runs smoothly except submit function. If I change the submit function with another function such as "show();" it works. Why doesn't it run this submit function?
$(document).ready(function() {
$('#submit').click(function() {
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if (email == "" || password == "") {
$('.division').show();
} else {
$('#form').submit();
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" method="post" action="run.php">
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="checkbox" checked="checked" id="keep" value="yes">
<label for="keep">Keep login</label>
<input type="submit" id="submit" value="Sign in" onClick="return false;">
</form>
The problem is that you've given your submit button the id "submit". Browsers add elements to the form object using the id, so the normal submit function of the form is being replaced with a reference to your submit button.
Change the name (and probably id) of the submit button to (say) submit-btn and it will work. Live Example
Separately from that, though, I wouldn't hook click on the submit button at all; I'd hook submit on the form element, since forms can be submitted in other ways (pressing Enter in certain form fields, for instance).
Example: Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script>
$(document).ready(function(){
$('#form').submit(function(e){
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if( email == "" || password == "") {
$('.division').show();
e.preventDefault(); // Don't allow the form submission
}else{
$('#form').submit();
}
})
});
</script>
<!-- Using GET rather than POST, and no action
attribute, so that it posts back to the jsbin page -->
<form id="form" method="get">
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="checkbox" checked="checked" id="keep" value="yes">
<label for="keep">Keep login</label>
<input type="submit" value="Sign in">
</form>
<div class="division" style="display: none">Please fill in an email and password</div>
</body>
</html>
In your input element, you have onClick="return false;"This onClick function is being given priority over the click handler that you defined in jQuery. If you remove the onClick portion of your input element, your jQuery code will run.
Aside, there is a problem with your submit code in that it never actually prevents the POST to the server. See my edit below:
if( email == "" || password == "") {
$('.division').show();
return false;
}else{
('#form').submit();
}
You must explicitly return false to prevent the form from submitting to the server. Alternatively, you can just remove the else clause altogether, due to the fact that if the function doesn't explicitly return false, it will complete and continue with the form submission.
Also note that for form submissions, it is typically better to use the onSubmit event as opposed to the onClick event, since forms can technically be submitted by hitting the 'enter' key as well as clicking the submit button. When onClick is used, the submission is not triggered via hitting the enter key.

My JavaScript Validation Form Wont Recognize Filled Inputs

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")

Why my form doesn't validate correctly?

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. ;)

Categories