Javascript - how to correctly verify form data? - javascript

I have a form with a few text inputs and also with one file-type input, in which I attempt to verify, if the selected file is PDF. I am doing that this way:
$("#myform").bind("submit", function() {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
alert('ERROR!');
}
});
But in the part of code above is one lack - if all inputs except the file-input (lets sat the file is DOC) are valid (=> file-input is not valid) and I click on the SUBMIT button, then is displayed alert message ERROR!, but the form is sent.
How can I "stop" sending the form, if the file type is not valid?

Try this:
$("#myform").bind("submit", function(e) {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
e.preventDefault(); //Prevents the default action which is form submit
alert('ERROR!');
}
});

You can shorten the code by doing this:
if (!(/\.pdf$/i).test($('#file_input').val())) {
// not valid, do what you like here
// return false to prevent submit
return false;
The form is prevented from submitting by returning false; preventDefault on the form submit event is not working in IE 7/8, return false does the job.

In a jQuery callback function bound to an event you have two options.
You can pass a reference to the event to the anonymous function and call e.preventDefault():
$('#myform').bind('submit', function(e) {
e.preventDefault();
// Your code
});
e.preventDefault() prevents the default functionality (in this case, submitting the form).
Or you can return false to both prevent the default functionality and prevent the event from bubbling; the same as calling e.preventDefault(); e.stopPropagation().

You have 2 ways:
Keep your code as it is and add return false:
$("#myform").bind("submit", function() {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
alert('ERROR!');
return false;
}
});
change the function signature to accept the event and use the preventDefault():
$("#myform").bind("submit", function(e) {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
alert('ERROR!');
e.preventDefault();
}
});

Related

Prevent beforeunload function from executing if submit button is clicked

I have the following function that gives a warning to the user if they are exiting the page when the $('.article_div textarea') form field is populated.
$(window).on('beforeunload', function(event) {
var unsaved = "Are you sure you want to exit?";
var text = $('.article_div textarea').val();
if (text.length > 0){
return unsaved;
}
});
However, I would like to prevent this popup from executing when they click the submit button to the actual form.
How can I ammend the function to account for this? The element of the submit button is
$('button.submit_post').
You can create a boolean which gets positive when you click on submit Or remove the event of unload when clicked. The code will be as follows:
var isSubmitClicked = false;
$('button .submit_post').on("click",onClick);
function onClick(e){
isSubmitClicked = true;
}
$(window).on('beforeunload', function(event) {
if(isSubmitClicked){
isSubmitClicked = false;
return;
}
// Rest of your method.
}
How about binding a event handler to the submit event instead of the submit button element?
Maybe like this:
var submitted = false;
$('form').on("submit", function() {
submitted = true;
console.log('submitted');
});
$(window).on('beforeunload', function(event) {
if(submitted){
submitted = false;
console.log('aborted because of submit');
return;
}
console.log('rest of code');
// Rest of your method.
});

event.prevendefault() not working inside a function that has an each() function

I have function that will do a simple validation, if every input text is empyt an alert will pop up, and the program will stop. Function will fire up after a click of a button. I'm allready passing the event, but somehow the event.PreventDefault() not working, so still accessing the server side code.
Below is the function to do simple validation.
var checkRequired = function(event)
$('.box-load .requir').each(function(index,item) {
var index = $(item).data('index');
if(index === 'text') {
if ($(item).val() == "") {
$(this).focus();
alert('Please input the required parameter');
event.preventDefault();
}
}
});
}
For the trigger the function I use this code:
$(document).on('click','.box-load .btn-save', function(event) {
event.preventDefault();
checkRequired(event);
Bellow the checkRequired(), I'm gonna do an ajax request. What i want is, if one of the input text is empty, the event is stop. But with that code, is not working. Any suggestion?
Thanks in advance.
if you call event.preventDefault(), default action of the event will not be triggered.
$(document).on('click','.box-load .btn-save', function(event)
{
checkRequired(event);
event.preventDefault();
event.preventDefault() should be outside the for loop.
var checkRequired = function(event)
{
$('.box-load .requir').each(function(index,item) {
var index = $(item).data('index');
if(index === 'text') {
if ($(item).val() == "") {
$(this).focus();
alert('Please input the required parameter');
}
}
});
event.preventDefault();
}
event.preventDefault() will just stop the default action, not stop your function call. If you don't specifically return from your function, it will go on and launch the ajax.

JQuery check required fields

I have created this function in JQuery:
function CheckRequired() {
var ret = true;
$(".required").each( function() {
var check = $(this).val();
if(check == '') {
//alert($(this).attr("id"));
ret = false;
}
});
if(!ret) {
alert("One or more fields cannot be blank");
return false;
}
}
on my forms submit buttons, i run this onClick
<input type="submit" onClick="CheckRequired();" />
if any fields in the form with a class of required have a blank value the error will alert to the user and the form should not submit.
the alert is showing, however the form still seems to be submitting
use preventDefault. This method makes sure the default action of the event will not be triggered.
function CheckRequired(event) {
var ret = true;
$(".required").each( function() {
var check = $(this).val();
if(check == '') {
//alert($(this).attr("id"));
event.preventDefault();
}
});
if(!ret) {
alert("One or more fields cannot be blank");
event.preventDefault();
}
}
To prevent form from submission you should bind event to form's onsubmit, and return function result
<form onsubmit="return CheckRequired()" />
Also, as you already use jquery it would be much more convenient to bind events in javascript:
$('#form_id').submit(function(){
//your form submit code
})
I think you have to prevent the default submission action by using event.preventDefault(); as noted here:
Prevent submit button with onclick event from submitting

Stop redirect in JavaScript

I have a function which verifies if some fields have been filled out (if length > 0) before submitting. If it fails to submit, I don't want to redirect the client at all. Right now, I have the following:
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
document.getElementById('my_form').submit();
return void(0);
}
else
{
document.getElementById('my_form').action = null;
}
}
However, it doesn't matter if verify() returns true or not, I still redirect the client and wipe her inputted fields. How do I keep the client on the page if a required field is blank? (I don't want to lose her currently filled out form...)
Also, I can't use the slick JQuery libraries, since it's not supported on some older browsers. (I'm trying to capture the most general audience.)
This is how I would try to solve this:
document.getElementById('my_form').onsubmit = function( e ){
var event = e || window.event;
// function payload goes here.
event.returnValue = false;
if ( event.preventDefault ){ event.preventDefault(); }
return false;
}
Can be used with event delegation too.
return false to the form!
<form onsubmit="return onSubmit()">
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
return true;
}
else
{
return false;
}
}
to stop the form from submitting, return false from your onSubmit

Javascript:Block form submit on Enter Key press

I have a web page where i have 2 forms when i click the enter key, I am calling a javascript function to force the page to load another page.My code is
function SearchUser()
{
var text = document.getElementById("searchItem").value;
text = text == "" ? -1 : text;
var by = document.getElementById("listBy").value;
var on="";
if(by==1)
{
on="USERNAME";
}
else if(by==2)
{
on="FIRSTNAME";
}
else if(by==3)
{
on="EMAIL_ID";
}
gotoUrl="userlist.php?searchItem="+text+"&onSearch="+on;
alert(gotoUrl);
window.navigate=gotoUrl;
}
and
$(document).ready(function()
{
$("#frmUserListSearch").keyup(function(event)
{
if(event.keyCode == 13)
{
SearchUser();
}
});
});
But the page is doing a form submit when the SearchUSer function being called.I am getting the correct url in the alert.But The page is not loading in the brower
Any Ideas ???
Thanks in advance
if (document.addEventListener) {
document.getElementById('strip').addEventListener('keypress',HandleKeyPress,false);
} else {
document.getElementById('strip').onkeypress = HandleKeyPress;
}
function HandleKeyPress(e) {
switch (e.keyCode) {
case e.DOM_VK_ENTER:
if (e.preventDefault)
e.preventDefault();
else e.returnValue = false;
}
}
EDIT due to original Question edit:
all you need is:
$(document).ready(function()
{
$("#frmUserListSearch").keyup(function(event)
{
if(event.keyCode == 13)
{
SearchUser();
if (e.preventDefault)
e.preventDefault();
else e.returnValue = false;
}
});
});
edited to reflect comment
Returning false often does the trick.
http://javascript.about.com/library/bldisdef.htm
I have two recommendations. First, use the keydown event instead of keyup (it catches "enter" before submit better). Second, in your SearchUser() function, use window.location instead of window.navigate to go to the other page.
$(document).ready(function() {
$("#frmUserListSearch").keydown(function(event) {
if(event.keyCode == 13){
SearchUser();
return false;
}
});
});
NOTE: Don't forget to remove the "alert()" inside the SearchUser() function as it causes the form to submit before navigating away from the page.
You can do this by using the action attribute of the form, without having to deal with key events, granted that you will later need javascript to take action on the control that submits the form.
<html>
<head>
<script type="text/javascript">
function donothing() {}
</script>
<body>
<form action='javascript:donothing()'>
...
</form>
</body>
</html>

Categories

Resources