Conflict on javascript form validation - javascript

I have implemented a simple javascript validation but the validation and the form submission never happen together ...
When i use "onsubmit" (like below) it will goto the next page without validation
if i use "onclick" on the end of the form
<input type="button" name="submit" id="send" value="Search Flights" onclick="return validate_booking_form();" />
</form>
it will validate the input .. but the form wont be submitted even the correct input
This is the code i have used
//Javascript Validation
function validate_booking_form()
{
chk_fromcity();
chk_tocity();
chk_depature_date();
}
function chk_fromcity()
{
var from_city = $('#from_cities').val();
if (from_city == '')
{
$("#from_cities").removeClass('fieldInput');
$("#from_cities").addClass('error');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('Please Enter a City').addClass('errormsg');
})
}
else
{
$('#from_cities').removeClass('error');
$('#from_cities').addClass('fieldInput');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('').removeClass('errormsg');
})
}
}
and the form
<form method="POST" action="../controller/booking.php" name="search_flights_names" onsubmit="return validate_booking_form();" >
/// Form content
<div class="form_input_container">
<div class="form_input">
<input type="text" id="from_cities" name="from_city" class="fieldInput" onblur="return chk_fromcity()" />
</div>
</div>
<input type="submit" name="submit" id="send" value="Search Flights" />
</form>

Submit is the proper button to use.
Try putton onsubmit in your form element and have the validation occur there instead of on the click event. That way pressing enter won't bypass all of your validation.

Try using Jquery validate. I think it should pretty much solve your problem

return false from chk_fromcity() to stop the form posting to action.
function chk_fromcity()
{
var from_city = $('#from_cities').val();
if (from_city == '')
{
$("#from_cities").removeClass('fieldInput');
$("#from_cities").addClass('error');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('Please Enter a City').addClass('errormsg');
});
return false;
}
$('#from_cities').removeClass('error');
$('#from_cities').addClass('fieldInput');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('').removeClass('errormsg');
})
// return true; // default is true which is why you were passing the validation
}

Related

empty check for multiple form in a page separately

I have two forms (consist with input,textarea,checkbox) in a page. I want check emptiness of these forms separately on click seperate button.
I use the following script. But it shows empty message if any of these form input is empty.
$('#submit').click(function(e) {
var empty = false;
$('input, textarea').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
alert("empty");
e.preventDefault();
}
else {
document.getElementById("contact").submit();
}
})()
Never assign stuff to submit buttons
Do not submit a form from a submit button if you have chosen to use preventDefault if something wrong. It could submit the form twice
$(function() {
// on the submit event NOT the button click
$('form').on("submit", function(e) { // any form - use .formClass if necessary to specific forms
var empty = false;
$("input, textarea", this).each(function() { // this form's inputs incl submit
if ($.trim($(this).val()) == "") { // trim it too
console.log(this.name,"empty")
empty = true;
return false; // no need to continue
}
});
if (empty) {
alert(this.id + " is empty"); // or set a class on the div
e.preventDefault(); // cancel submission
}
});
});
div {
border: 1px solid black;
width:500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form id="form1">
<div>
<input type="text" value="" name="field1" /><br/>
<textarea name="field2"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
<hr/>
<form id="form2">
<div>
<input type="text" value="" name="field3" /><br/>
<textarea name="field4"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
You could also add required to the fields
You need to restrain the handler to the form containing the clicked button:
$('#submit').click(function(e) {
var form = $(this).parents('form:first');
var empty = false;
$('input, textarea', form).each(function() {
// the rest is the same
I'd also like to point out that you cannot have the same ID on multiple controls, so
$('#submit')
should always return exactly one button. You should do something like this, where you distinguish the buttons by class instead:
<input type="submit" id="submitA" class="submitButton">
<input type="submit" id="submitB" class="submitButton">
and select with
$('.submitButton')
you know you can also use jquery to reset the form like so
form.resetForm();

Validate all form data before submitting

I have created a form in HTML and have use onblur event on each and every field and it is working very fine. The problem is when i click on submit button(which will send data to a servlet) the data is submitted even if it is invalid. Here is an example.
<html>
<head>
<script>
function check()
{
if(checkName()==true)
return true;
else{
alert('vhvh');
return false;
}
}
function checkName()
{
var uname=document.enq.Name.value;
var letters = /^[A-Za-z, ]+$/;
if(uname.match(letters))
{
document.getElementById('Name').style.borderColor = "black";
return true;
}
else
{
document.getElementById('Name').style.borderColor = "red";
//alert('Username must have alphabet characters only');
//uname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="enq" method="post" action="Enquiry" onsubmit="check()">
<input class="textbox" id="Name"style="margin-top:10px;font-size:16px;" type="text" name="Name" placeholder="Full Name" onblur="checkName()" required /><br><br>
<input class="button" type="submit">
</form>
</body>
</html>
How can i resolve this issue?
use
<input class="button" type="button">
and put a onclick event like this:
<input class="button" type="button" onclick="this.submit()">
so you can manipulate data before you subimit it.
There is an "onsubmit" event that allows you to control form submission. Use it to call your validation functions, and only then decide if you want to allow the user to submit the form.
http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html
You have to use it in the following way if you want it to prevent the form submission:
<form onsubmit="return check()">

my jquery form validation is not working as i hope it should

I have some javascipt code here that validates a user form. When the user inputs the correct answer it tells them and gives them the link to the next question. At least, that's what it is supposed to do. When i click the form it reloads the page but it should not because i added return false.
the div tra holds 35
and the div usermsg is the user inputted value.
<script>
$("#submit").click(function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6<>rightanswer)
{
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else
{
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
</script>
Any ideas why this is not working?
It should be
if (clientmsg6 != rightanswer)
not
if (clientmsg6<>rightanswer)
To prevent a form submission, you need to return false on the form itself instead of on the submit button. Your code should become:
HTML
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="submit" value="Submit" />
</form>
JS (please note the line where you have clientmsg6, you have a syntax error)
$("#myform").on('submit', function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6 != rightanswer) { //This line was also wrong, should be != instead of <>
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else {
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
Alternatively, you can keep your existing code by changing your submit button to be just a plain old button, but you will lose the extra functionality of the user being able to hit the enter key and performing the same action.
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="button" value="Submit" />
</form>
Instead of using .html(), try using .text()
if #submit is a link tag otherwise use the form ID and the submit event
$("#submit").click(function(e){
e.preventDefault()
...
...
...
});
You need to attach handlers once the document has finished loading.
Wrap your script in the following
<script>
$(function() {
// script
});
</script>

Javascript form validation onSubmit not triggering

please can someone help. this form validation is not triggering.. It's really frustrating me. I'm a PHP developer rather than JS so i'm struggling a bit with this even though it's clearly something very simple. I'm just trying to validate the form based on the delete box being ticked.
Nothing appears when I click submit. It just submits the form so it must be returning true.
function deleteVal(chk) {
var chk;
// If the checkbox has been set to delete
if (chk.checked == "delete") {
var ok=confirm("You are about to delete the selected images below.\nAre you sure you want to do this?");
if (ok) {
// Submit
return true;
} else {
// Don't submit
return false;
}
}
// Delete box was not ticked so return true and submit form
return true;
}
</script>
<form action="" method="POST" onSubmit="return deleteVal(delete)">
<label>Delete images?</label><input type="checkbox" name="delete" value="delete" />
<input type="submit" name="submit" value="Submit" />
</form>
You need to get the checked value properly like so and see if it is true or false.
var chk = document.getElementById('delete');
// If the checkbox is checked
if (chk.checked == true) {
Then you do not need to pass a variable to the function, however, you do need to give you checkbox an id.
<form action="" method="POST" onSubmit="return deleteVal();">
<input type="checkbox" name="delete" id="delete"/>
<input type="submit" name="submit" value="Submit" />
</form>
Tested code - http://pastebin.com/FdWdeSCN

How to do something before on submit?

i have a form which has a button that submits the form. I need to do something before submits happen. I tried doing onClick on that button but it happens after the submit.
I can't share the code but, generally, what should I do in jQuery or JS to handle this?
If you have a form as such:
<form id="myform">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$('#myform').submit(function() {
// DO STUFF...
return true; // return false to cancel form action
});
Update; for newer JQuery versions (to avoid deprecation warnings), try:
$('#myform').on('submit', function() {
// ...
return true;
});
Assuming you have a form like this:
<form id="myForm" action="foo.php" method="post">
<input type="text" value="" />
<input type="submit" value="submit form" />
</form>
You can attach a onsubmit-event with jQuery like this:
$('#myForm').submit(function() {
alert('Handler for .submit() called.');
return false;
});
If you return false the form won't be submitted after the function, if you return true or nothing it will submit as usual.
See the jQuery documentation for more info.
You can use onclick to run some JavaScript or jQuery code before submitting the form like this:
<script type="text/javascript">
beforeSubmit = function(){
if (1 == 1){
//your before submit logic
}
$("#formid").submit();
}
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />
make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.
Form:
<form id="formId" action="/" method="POST" onsubmit="prepareForm()">
<input type="text" value="" />
<input type="submit" value="Submit" />
</form>
Javascript file:
function prepareForm(event) {
event.preventDefault();
// Do something you need
document.getElementById("formId").requestSubmit();
}
Note: If you're supporting Safari (which you probably are) you'll need to pull in a polyfill for requestSubmit()

Categories

Resources