I have the following html form
<form action="/newPost" id="submit_new" method="get"><div class="iwill">
<div class="iwill-holder">
<div class="txt"></div><div class="f"><input class="text" id="quickpost" name="quickpost" type="text" value=""></div>
<div class="img regularProgress" alt="Processing..."><input alt="Continue" class="iwill-btn movable" id="continue_submit" src="<?=$config['http']?>images/btn-2-continue-gray.png" type="image"></div>
</div>
</div>
</form>
and here is the jquery function :
$('#submit_new').submit(function() {
var error = 0;
var quickpost = $("#quickpost").val();
if( quickpost == '' ) {
$("#quickpost").effect("shake", { times:3 }, 50);
$('#quickpost').css("color","red");
$('#quickpost').css("border","red 1px solid");
error = 1;
}else{
$('#quickpost').css("border","gray 1px solid");
$('#quickpost').css("color","black");
error = 0;
}
if(errorCounter > 0){
return false;
}else{
$.ajax({
url: 'sendPost.php?quickpost='+quickpost,
success: function(data) {
$('#result').prepend(data).slideDown('slow', function() {});
}
});
}
return false;
});
technically I am trying to post the form values using ajax, but whatever I do the form still gets submitted to action page. I have tried to even make all paths lead to false but its not working
Try preventing the default behavior
$('#submit_new').click(function(e) {
e.preventDefault();
...
You also have a typo
if(errorCounter > 0){
return false;
}else{
should be:
if(error > 0){
return false;
}else{
$('#submit_new').submit(function(e) {
e.preventDefault();
//other stuff
});
You need a preventDefault() in the submit function.
I got a version still use return false to prevent form submit
http://jsfiddle.net/pKR6G/2/
NB: I've commented out the line of shake effect so I don't need to include jQueryUI.
The event listener method does not care what you return from a listener function. You need to use the jquery preventdefault method on the passed in event object.
Related
I have a link:
<a id="trigger" href="file.pdf" onclick="return false;">Download pdf</a>
and this Javascript:
// Check validation and enable or disable the <a> tag
if( $('#input_1').hasClass('valid') )
{
$('#trigger').prop("onclick", null);
}
else // disable the button
{
$('#trigger')[0].onclick = function () { return false; }
}
However when the validation fails the button still works even with the
onclick="return false;"
Can someone help me understand this and how to efficiently disable the anchor tag?
UPDATE: fixed $('#trigger')[0].onclick = function () { return false; } but once this makes it to the anchor tag the button still serves the file download.
You need to do either of the following:
$('#trigger')[0].onclick = function () {return false;}
or
$('#trigger').click(function () {return false;});
if( $('#input_1').hasClass('valid') )
{
$('#trigger').attr("onclick", null);
}
else // disable the button
{
$('#trigger').on('click', function(e) { e.preventDefault(); } );
}
Better use .preventDefault method.
Also use .prop method only for form controls.
For cases like this, I like to make it a tad harder for people to by-pass the front-end security. (But only a little but, obviously this can easily be by-passed.)
Call event.preventDefault() if not valid
Add class to element if not valid. This class will have pointer-events set to none so it won't register clicks
Check if a global JS variable has been set
var valid = false;
$("#valid-checkbox").change(function() {
var $this = $(this),
trigger = $("#trigger");
if ($this.is(":checked")) {
valid = true;
$this.val("valid");
trigger.removeClass("disabled");
} else {
valid = false;
$this.val("invalid");
trigger.addClass("disabled");
}
});
$("#trigger").click(function(e) {
if (valid === false || $(this).hasClass("disabled") || $("#valid-checkbox").val() == "invalid") {
e.preventDefault();
}
});
.disabled {
opacity: 0.5;
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="trigger" href="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" class="disabled" target="_blank">Download pdf</a>
<input type="checkbox" value="invalid" id="valid-checkbox">
<label for="valid-checkbox">Valid?</label>
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
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
I'm working on a project where I have some error checking. However, the form wanted to submit each time so I had to break the submit. Here is what I did.
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "order-form" }))
{
...
<input type="submit" name="btnSaveOpv#(item.Id)" value="#T("Admin.Common.Save")" id="btnSaveOpv#(item.Id)" class="adminButton" style="display: none;" onclick="SaveBtn(#item.Id);" />
...
var originalIssuedQty = 0;
function SaveBtn(id) {
var quantity = parseInt($("#pvQuantity" + id).val());
var issuedQty = parseInt($("#pvIssuedQty" + id).val());
var stockQty = parseInt($("#hfStockQty" + id).val());
var availableStockQty = stockQty + parseInt(originalIssuedQty);
//Issued Quantity cannot exceed Quantity (you can't issue more than requested)
if (issuedQty > quantity) {
alert("Issued Quantity cannot exceed Quantity.");
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
//Make sure Issued Quantity is within Available Stock Quantity
if (issuedQty > availableStockQty) {
alert("There is not enough Products in Stock to issue this amount.");
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
//Present confirmation
var result = confirm('#T("Admin.Common.AreYouSure")');
if (!result) {
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
else {
$("#order-form").submit(function (e) { this.submit(); });
//$("#order-form").submit(function (e) { return true; });
}
}
...
}
Here is the problem. Whenever I try to submit the first time without triggering any of my error checking, things work. When I trigger the error checking, things work. However, if I fix the error and try to submit again, the page merely refreshes. Any ideas on this would be very helpful. Thanks.
You are making things too complicated.
This is a basic template on how you do validation and how you stop the form from submitting when it's not valid:
$(function() {
$("#order-form").submit(function (e) {
var isValid = false;
// Do your validation here and put the result in the variable isValid
if ( !isValid ) {
e.preventDefault(); // If the form is invalid stop the submit, otherwise proceed
}
});
});
Every time you call $("#order-form").submit(function (e) { whatever });, you add an additional handler function. It doesn't remove the handlers you've already added. This is probably why it breaks.
Repeatedly changing the submit event handler is a messy way to do it. Instead, you should have a single function which handles the submit event, and that function should do (or call) the error checking, and preventDefault() if necessary (like ZippyV is suggesting).
I want a jQuery form submit handler to respect any previous submit handlers, including ones added with onsubmit.
I'm trying to detect the previous handler's return value but can't seem to do it:
<form><input type="submit" /></form>
<script type="text/javascript">
$('form')[0].onsubmit = function() { return false; }; // called first
$('form').submit(function(e) {
console.log(e.result); // undefined
console.log(e.isDefaultPrevented()); // false
console.log(e.isPropagationStopped()); // false
console.log(e.isImmediatePropagationStopped()); // false
});
</script>
Is there a way to do this?
I found one non-jQuery way to do this:
var form = $('form')[0];
var old_onsubmit = form.onsubmit;
form.onsubmit = function() {
if ($.isFunction(old_onsubmit)) {
if (old_onsubmit() === false) {
console.log("false");
return false;
}
}
console.log("true");
return true;
}
But I'd much prefer detecting this from the jQuery-bound submit handler