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();
});
});
Related
I use javascript to validate my form input and it works fine but the form still gets submitted when errors are not corrected.
How do I prevent form submission until the user makes corrections?
Sample Code Below;
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456") {
$(".validate").show();
} else {
$(".validate").hide();
}
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<div class="validate"><span style="color: red;"><b>Phone in use!</b></span></div>
<button href='/' type='submit' id="submitForm">Process</button>
</form>
To write a helpful answer, I made a small refactor, rewriting isphone to be a reusable validation function that just returns true or false. I renamed it too. Now we can reuse the validation logic in different places.
form elements emit a submit event just before they are actually submitted. We must listen for the sumbit event, and if validation fails, we can return false which will cancel the event, and therefore preventing form submission.
$('.validate').hide();
$('body').on('blur', '#phone', function() {
var value = $(this).val();
if (isPhoneInUse(value)) {
$(".validate").show();
} else {
$(".validate").hide();
}
});
$('#submitForm').on('submit', function(e) {
var value = $("#phone").val();
if (isPhoneInUse(value)) {
// validation failed. cancel the event
console.log("not submitting");
return false;
}
})
function isPhoneInUse(phone) {
return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<div class="validate"><span style="color: red;"><b>Phone in use!</b></span></div>
<button href='/' type='submit' id="submitForm">Process</button>
</form>
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 am trying to write a very simple jQuery function which will have two main properties. The first one will be to check if the field is empty or not. The second one will be if the field is not empty to execute a form which will lead to a PHP coded page. I am very new to jQuery and I will be very grateful if someone can point where exactly is my mistake. Thank you in advance.
function Captcha() {
$('#Button').click(function() {
if ($("#Field").val().length == 0) {
alert("Please fill the box");
return false;
} else {
alert("Your code is saved");
return true;
}
});
}
$(document).ready(function() {
Captcha();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="success.php" id="Alpha" method="post" onsubmit="return Captcha();">
<input id="Field" type="text" placeholder="Enter key here">
<button id="Button" type="submit" form="Alpha">Confirm</button>
</form>
Don't work with the button's click event, work with the form's submit event because a form can be submitted via the keyboard and therefore the button can be circumvented.
You can see a working version here (Stack Overflow prevents submit code from working in the snippet environment below.)
$(function() {
$('#Alpha').on("submit", function() {
if ($("#Field").val().length == 0) {
alert("Please fill the box");
return false;
} else {
alert("Your code is saved");
return true;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="success.php" id="Alpha" method="post" onsubmit="return Captcha();">
<input id="Field" type="text" placeholder="Enter key here">
<button id="Button" type="submit" form="Alpha">Confirm</button>
</form>
You would want to validate the form fields when you actually submit the form. When you click on the button you are still in the process of triggering the submit.
Try changing this:
$('#Button').click(function() {
Into this:
$('#Alpha').on('submit', function() {
See if that helps.
Here is my code example
<form action="next2.php" method="post" name="next2" id="next2" onsubmit="return submitForm();">
Below is my function
<script type="text/javascript">
function submitForm()
{
var name = document.getElementById("name").value;
return false;
}
</script>
On press, the form still submit, but if i change
onsubmit="return false;"
then the form won't submit, how do I use the function to return false as i need do some if else validation
<script type="text/javascript">
function submitForm() {
return false;
}
</script>
<form
action="next2.php"
method="post"
name="next2"
id="next2"
onsubmit="return submitForm();"
>
submit is already a function for the form, you should call your JavaScript function something different, for instance submitForm as in the above.
just remove the semicolon in your function and place a alert in your function to make sure whether the function is called first.and then try to add validation
I like to make an invisible button for the actual submit which is only triggered after form validation:
function validate() {
var valid = true;
$.each($('input'), function(){
valid = valid && $(this).val().length > 0;
})
if (valid) {
$('#realSubmit').click();
} else {
alert('Please fill out all fields!');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="next2.php" method="post" name="next2" id="next2" onsubmit="return submit();">
<input type="text" placeholder="Enter Name" />
<input type="password" placeholder="Enter Password" />
<button type="button" onclick="validate()">Submit</button>
<button type="submit" id="realSubmit" style="display:none"></button>
</form>
I want make validation jquery without using from plugin, problem is here that after click on button and get alert(if field is empty) it go to url # that there is in <form action="#"....
I want if get alert(mean if field is empty) 'input is empty' not go to url that there is in ...action="#"..., if filed has value it go to url. i can not use from ajax call or preventDefault or window.location(Because one from field is input:file).
Example: http://jsfiddle.net/gb7nh/1/
How can fix it?
<form action="#" method="POST">
<input type="text" name="name">
<button id="cli">Submit</button>
</form>
$('#cli').live('click',function(e){
//e.preventDefault();
if($('input[type="text"]').val()=='')alert('input is empty')
})
Bind to form submittal instead, and return false to prevent the form from submitting.
<form action="#" method="POST" id="myform">
<input type="text" name="name">
<button id="cli">Submit</button>
</form>
$('#myform').submit(function() {
var valid = true;
$('input[type="text"]').each(function() {
if ($(this).val().length == 0) {
alert('A field is empty!');
valid = false;
return false;
}
});
if (!valid) {
return false;
}
});
This should do the trick for you:
<button id="cli" onclick="return clickButton();">Submit</button>
And it's corresponding JavaScript
function clickButton(){
if($('input[type="text"]').val()==''){
alert('input is empty');
return false;
}
}
Probably you need to return false in case when you show alert woth errors:
$('#cli').live('click',function(e){
//e.preventDefault();
if($('input[type="text"]').val()=='')
{
alert('input is empty');
return false;
}
});
Code: http://jsfiddle.net/gb7nh/2/
I wolud do it like Elliot. Only i would have used:
<form action="#" method="POST" id="myform">
<input type="text" name="name">
<button id="cli">Submit</button>
</form>
$('#myform').submit(function() {
if (!$('input[type="text"]').val()) {
alert('input is empty');
return false;
}
});
This.
if (!$('input[type="text"]').val())
Instead of:
if ($('input[type="text"]').val()=='')