I'm making some message validation with javascript using setCustomValidity() method. So when I attach onsubmit in my form it won't display message in input field but when I use onclick it dispay message.I understand difference between onlclick and IonsubmitI function. But why message is not displayed when I use onsubmit function?
For example.
<form id="myForm" onsubmit="subForm">
<input type="email" name="email" id="email" required>
<input type="submit" name="subit" id="submit">
</form>
<script type="text/javascript">
var mail = document.getElementById("email");
function subForm() {
if (mail.value == "") {
mail.setCustomValidity("Your input field is empty!");
}
}
</script>
Related
Simple html form with some JavaScript code to check if user name is empty and then display error message otherwise submit the form.
First part works fine when the user name is empty.
Second part does not work once I click the submit button when the user name is not empty.
What is wrong with the code and how can I submit the form correctly?
let userName = document.getElementById('uname');
let form =
document.querySelector('#myForm');
form.addEventListener('submit',function(e){
e.preventDefault();
if(userName.value === ''){
alert('user name is required');
}
});
<form method="get" id="myForm">
<div>
<input type="text" class="form-control" id="uname" name="uname">
</div>
<button type="submit" name="submit">send</button>
</form>
That is because of using preventDefault. You are calling e.preventDefault(); even there is no error while you just need to call the function when form is not valid.
So put e.preventDefault(); in if part
let userName = document.getElementById('uname');
let form =
document.querySelector('#myForm');
form.addEventListener('submit',function(e){
if(userName.value === ''){
alert('user name is required');
e.preventDefault();
}
});
<form method="get" id="myForm">
<div>
<input type="text" class="form-control" id="uname" name="uname">
</div>
<button type="submit" name="submit">send</button>
</form>
You need to conditionally call the e.preventDefault() so that it doesn't prevent the submit behaviour of the form.
You only need to prevent the form submit behaviour while showing the alert box.
preventDefault() will tell the browser to avoid the default action of the form (submit action)
Move preventDefault in the condition where the username is empty:
let userName = document.getElementById('uname');
let form =
document.querySelector('#myForm');
form.addEventListener('submit',function(e){
if(userName.value === ''){
alert('user name is required');
e.preventDefault();
}
});
<form method="get" id="myForm">
<div>
<input type="text" class="form-control" id="uname" name="uname">
</div>
<button type="submit" name="submit">send</button>
</form>
I'm trying to check if the textbox is empty for my form. However, whenever I try to hit submit instead of an alert box message, telling me Firstname is empty I get "Please fill out filled".
('#submit').click(function() {
if ($('#firstname').val() == '') {
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Firstly I'm assuming that the missing $ is just a typo in the question, as you state that you see the validation message appear.
The reason you're seeing the 'Please fill out this field' notification is because you've used the required attribute on the field. If you want to validate the form manually then remove that attribute. You will also need to hook to the submit event of the form, not the click of the button and prevent the form submission if the validation fails, something like this:
$('#elem').submit(function(e) {
if ($('#firstname').val().trim() == '') {
e.preventDefault();
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Personally I'd suggest you use the required attribute as it saves all of the above needless JS code - unless you need more complex logic than just checking all required fields have been given values.
Because you have the required property set.It is giving you Please fill out field validation as the error message.It is the validation that HTML5 is performing.
For this please make one function like :
function Checktext()
{
if ($('#firstname').val() == '') {
alert('Firstname is empty');
return false;
}
else
{
return true;
}
}
now call this function on submit button click like :
<input type="submit" id="submit" value="Submit" onclick="return check();" />
I am using JavaScript to validate email. The problem is, when the email ids don't match, then one alert button will come. Once I click the button it still takes me to the other page, instead of same page to correct my mail id.
HTML:
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="validate()">
JavaScript:
function validate()
{
if(document.getElementById("email").value != document.getElementById("confirm_email").value)
alert("Email do no match");
}
You need to tell the submit button to not perform the submit
function validate()
{
if (document.getElementById("email").value!=document.getElementById("confirm_email").value) {
alert("Email do no match");
return false;
}
}
The problem is because You have taken button type=submit
Change input type='button'
<input type="button" name="submit" value="submit" class="button" onClick="validate()">
and submit form using javascript
document.getElementById("myForm").submit();
I case you want to validate only on submit then use
event.preventDefault();
and then validate but after successful validation you have to submit the form using js or jq. JS method is given above and jq method is:
$("form").submit();
You should add return false; in your if code block if you dont want the redirect.
Its the browser's default to refresh the page when the form is submitted. To prevent this refresh, add return false;.
Learn more: return | MDN
<html>
<head>
<script>
function validate(){
if(document.getElementById("email").value != document.getElementById("confirm_email").value){
alert("Email do no match");
return false;
}
}
</script>
</head>
<body>
<form action="formsubmit.php" method="post" onsubmit="return validate()">
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button">
</form>
</body>
</html>
Use the below javascript code, your html code is correct!
Well executing the JavaScript code in StackOverflow Script Runner won't run and occur erorrs. If input boxes with email and confirm_email id(s) are declared, this should work.
Hope it could help!
function validate(){
if(!document.querySelector("#email").value === document.querySelector("#confirm_email").value){
alert("Email do not match.");
}
}
/* In JavaScript, the ! keyword before the condition belongs to execute the statement if the given condition is false. */
It must prevent the form to get submitted if the validation is failed. so
return validate();
must be there. So if the validate function returns a false value then it will stop the form to be submitted. If the validate function return true then the submission will be done.
<form method='post' action='action.php'>
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="return validate();">
</form>
<script>
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate(){
if(!validateEmail(document.getElementById('email').value))
{
alert('Please enter a valid email');
email.focus();
return false;
}
else if(document.getElementById('email').value!=document.getElementById('confirm_email').value) {
alert('Email Mismatch');
confirm_email.focus();
return false;
}
return true;
}
</script>
Fix that and remove type=submit and use a function or use following code:
<script>
function check(){
//* Also add a id "submit" to submit button*//
document.querySelector("#submit").addEventListener("click", function(){
//* Perform your actions when that submit button will be clicked and close with this in next line*//
})</script>
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.
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);