jQuery: event.preventdefault(); - javascript

If I create the click events and their handler on my own, it is no problem for me to execute event.preventdefault() at the right place. But if there is an element, which already has registered click events and corresponding handler, I want to deactivate its further working (e.g. submitting) in a certain case.
This is the example:
There is a submit button on the page, with registered click elements (maybe about hundred validation routines.. ) and a variable (al) with a certain value. Be the instantaneous value of this variable = 5 (it is not the desired certain case -> with value = 3).
HTML
// other form elements
<input type="submit" name="next" value="go"/>
JavaScript with jQuery
var al = 3;
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
In this example I cannot prevent the form is being submitted. What is my mistake?
EDIT: event.preventDefault ist not the problem, sublime (my editor) corrects it anyway.
----- I WANT TO SIMPLIFY THE QUESTION ---------
That is a SubmitButon (this time from yii in the original context):
VIEW
echo CHtml::submitButton(
Yii::t ('Somethin', 'next'),
array(
'name' => 'next',
'onclick' => "checkDetails()"
));
JS
checkDetails() {
PREVENT_SUBMITTING
}
How should PREVENT_SUBMITTING look? What would prevent submitting in this case, without any condition?

change
event.preventdefault();
to
event.preventDefault();
you have to write the "D" as capital letter.

You can do this two ways
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
or
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
return false;
} else {
alert ('OK');
return true;
}
}
);

Now I have a working solution:
VIEW
echo PHtml::submitButton(Yii::t('Something', 'next'),
array(
'name' => 'next',
'onclick' => "return checkDetails(event)",
)
);
jQuery
function checkDetails (event) {
event.preventDefault();
event.returnValue =false; // for IE
return false;
}

$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);

Try this Change event.preventDefault();
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);

I recently needed to use .off() instead of .preventDefault(). I needed to intercept and block one event handler while still allowing the main click event to bubble up. Might be what you need.

Besides from this problem I ll suggestion you to separate the validation part e. g
Add another form input e.g proceed
<input type="hidden" name="proceed" value="0"/>
<input type="submit" name="next" value="go"/>
Add custom validation method
jQuery.validator.addMethod("validateSteps", function(value, element) {
return value == 3 ? false : true;
}, "*");
Add validation rule to you form
$("#your_form_id").validate({
rules: {
"proceed": {
validateSteps: true
}
},
messages: {
"proceed": {
validateSteps: "custom message"
}
}
});
You have to set proper value to proceed input field before. This way you do not need to wade through event issues. And its more customizable e.g if you have ten steps with different validation requirements on each step

Related

How to show native validation error for specific input on change event?

I have a classic HTML5 form. I would like using jquery/javscript to show the browser native error tooltip when the user change a specific input value. I would like to avoid the user try to submit the form to see all errors.
For that, I tried with the functions checkValidity() and reportValidity() but it works only if I add alert('test'); in my condition...so weird
JS script
myInputJqueryObject.on('change', function() {
if ( !this.checkValidity() ) {
this.setCustomValidity( 'Custom error !!!' );
var $form = $('#my-form');
if( $form[0].checkValidity() === false) {
$form[0].reportValidity();
//alert('test'); <-- works only if I active this line code
return true;
}
}
});
You do not need to check the form validity when you know that the input is invalid. You can omit if( $form[0].checkValidity() === false). Also you can reportValidity on the input itself.
And setCustomValidity takes some time to be applied to the input field. So you have to wrap reportValidity into setTimeout:
$('input').on('change', function() {
var self = this;
if (!self.checkValidity()) {
self.setCustomValidity('Custom error !!!');
setTimeout(function() {
self.reportValidity();
self.setCustomValidity('');
}, 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form"><input value="del me" required></form>
Based on 'Kosh Very' answer, I found the solution. It sounds good without bugs.
JS Script :
$('input').on('focusout', function() {
var self = this;
var validity = self.checkValidity();
if( !validity ){
if( self.validity.patternMismatch ){ //<-- Optionnal : Condition to keep others native message errors except Pattern.
self.setCustomValidity( 'Custom Error about pattern!!!' );
}
setTimeout(function() {
self.reportValidity();
self.setCustomValidity( '' ); //<-- Important to reinit
}, 1);
}
});

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.

Javascript - how to correctly verify form data?

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();
}
});

jQuery submit() - form is still sent

I have this
$("#formNewsletter").submit(function(){
return false;
})
It works as expected - the form is not submited.
When i write this, it seems like it is returning true (the form is being send)
$("#formNewsletter").submit(function(){
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
return false;
})
I would like to understand why is this happening and how can I make it work.
Thank you!
the property length isn't a method.
Use $("#newsletterSelSpec div").length > 0.
You can prevent the default behavior of an event using preventDefault() witch is a method in the first argument. (event).
$("#formNewsletter").submit(function(event) {
event.preventDefault();
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
});
Not sure, but the problem can be that the alert stops the process of the script and not the submit event.
$("#formNewsletter").submit(function(e) {
if ($("#newsletterSelSpec div").length > 0) {
alert("Good");
} else {
e.preventDefault(); // prevent the form submission
alert("Please add at least one speciality!");
}
});
NOTE
you're using .length(), but it should be .length only, that means
$("#newsletterSelSpec div").length

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