validate simple html form with JavaScript - javascript

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>

Related

Why's my form action still being triggered when validating the form despite using e.preventDefault()?

I'd like to display a message above the name field if the user submits a name with a length greater than 20. This means the form will not get submitted - in other words, the form's action won't be triggered.
I've tried almost every suggestion I could find to prevent the form action from being triggered upon form validation but nothing seems to be working.
I've hit a wall with this and can't figure out what I'm doing wrong. How can rectify this?
html:
<form method="POST" id="form" action="/post.php">
<span class="nameError"></span>
<input type="text" class="name" name="name" placeholder="Name" required/>
<input class="button" type="submit" value="Submit"/>
</form>
Here's my jquery:
let name = $('.name');
let nameError= $('.nameError');
$(document).ready(function() {
$('input[type=submit]').on('click', function(e) {
if (name.length > 20) {
e.preventDefault();
nameError.val("Too many characters!");
return false;
}
});
});
I have modified the logic for validation. Basically we need to capture the submit event for the form and use the correct jquery methods to retreive data based upon the selectors.
$(document).ready(function() {
$("#form").submit(function( event ) {
let name = $('.name').val();
let nameError= $('.nameError');
if (name.length > 20) {
nameError.text("Too many characters!");
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form method="POST" id="form" action="/post.php">
<input type="text" class="name" name="name" placeholder="Name" required/>
<label class="nameError"></label> <br/>
<input class="button" type="submit" value="Submit"/>
</form>

How can I disable the popup success message when the form is required to fill?

I am planning to display a Success message when clicked on the Submit button.
However, I would like to disable or hide the Success message whenever the form is required to fill.
So how can I do it by changing the code in script?
Please help me, I really appreciate your support!
This is my code:
<div class="contact-wrapper">
<main class="flex-container">
<section class="main-content">
<form class="contact-form" action="index.html" method="post" onsubmit="return false">
<input type="text" class="contact-form-text" placeholder="Name" id="name" required/>
<input type="email" class="contact-form-text" placeholder="Email" id="email" required/>
<input type="text" class="contact-form-text" placeholder="Title">
<textarea class="contact-form-text" placeholder="Type your message..."></textarea>
<button>Send</button>
<div class="alert">
<span class="message">Success: You Message Sent Successfully!</span>
</div>
</form>
</section>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var name = document.getElementById('email').value;
}
$('button').click(function(){
$('.alert').addClass("show");
$('.alert').addClass("showAlert");
$('.alert').removeClass("hide");
setTimeout(function(){
$('.alert').addClass("hide");
$('.alert').removeClass("show");
},3000);
});
</script>
Consider hiding the message initially and display it only on successful submission
<div class="alert hide">
<span class="message">Success: You Message Sent Successfully!</span>
</div>
you should show the alert only if the form validation returns true.
function validateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
if(name == '' || name == null || email == '' || email == null){
alert("Please Fill All Required Field");
return false;
}
return true;
}
$('button').click(function(){
if(validateForm()){
// your code for submission
// after successful submission display the alert message
$('.alert').removeClass("hide");
$('.alert').addClass("show");
$('.alert').addClass("showAlert");
}
});
I would suggest you to follow the standard format for form validation and form submission. link here

Form message validation using onsubmit function?

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>

Jquery: On form submit validate then allow default operation to continue

Wondering, is there a way to make a form execute default operation after preventingDefault and validating form fields.
$('#form').submit(function (e) {
e.preventDefault();
var isValid = true;
var name = $('#name').val();
if (empty(name)) {
isValid = false;
}
$(this).submit() // This will cause a stack overflow :)
});
After I complete the form validation I want to proceed as normal,
I thought of using onClick on the submit button, but users can trigger submit by hitting on the enter key, which I want to allow. Reason why I want to do this is so that the server can perform its operations like redirecting.
I am writing you a small example.
$(document).ready(function(){
$("#control_form").on("keyup", function(event){
post_control();
});
});
var post_control = function(){
var user_name = $("#user_name").val();
if ( user_name==null || user_name=="" || user_name.length < 4 )
$('.error').html("Username can not be less than 4 characters!");
else
{
$('.error').empty();
$('#control_form').removeAttr('onsubmit');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="users_form">
<form name="form" id="control_form" action="post_form" method="post" onsubmit="return false;">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name">
<input type="submit" value="Save">
</form>
<div class="error"></div>
</div>
Instead of using preventDefault, you can return true at the end of the function.
If you want to prevent the submission, you can return false.
Here's an example using your code. If you try to submit the form with an empty field, it won't submit. If you fill the field, it will:
$("#form").submit(function() {
var name = $("#name").val();
if (!name) {
$(".form-group").addClass("has-danger");
alert("Field is blank. Submit will be prevented.");
return false; // no submission
}
alert("Field is filled. The form will submit.");
return true; // form submits
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='form'>
<div class="form-group">
<label class="form-control-label" for="name">Name</label>
<input type="text" class="form-control" id="name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
CodePen Demo
check this it works.I tested it.
$(document).ready(function(){
$('#form1').submit(function (e) {
if($('#name').val() == ''){
alert('Name is empty');
return false;
}
$(this).submit();
});
});

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.

Categories