I have no idea if this is even possible, but I thought I would ask since it would be awesome if it is possible.
So basically I have a link with an onclick and in the onclick there are two calls. one to a function and another to _doPostBack.
The first function that is called is a simple function:
function CheckTerms() {
if (!document.Form.agreetoterms.checked) {
alert("Please check the terms and conditions.");
return false;
}
return true;
}
So basically if the check box isnt checked the alert happens and the page doesn't submit. If it is checked it submits. Right now even if it isn't checked, it shows the alert and executes the doPostBack and submits the page. The doPostBack is put into the link dynamically and I don't have access to it, which has made it harder for me. So any ideas or ways to abort it so it doesn't submit?
Thanks!
I'm assuming the _doPostback function handles the posting of the form, and that you don't want the anchor to move the page to the location of its href when clicked. preventDefault does this by preventing the anchor's default action from being taken when clicked.
var a = document.getElementById("yourAnchorId");
a.onclick = function(e){
e.preventDefault();
if (CheckTerms())
_doPostBack();
}
why can't you do the following:
function CheckTerms() {
if (!document.Form.agreetoterms.checked) {
alert("Please check the terms and conditions.");
return false;
}
else{
<<< call you function here >>>
}
return true;
}
Related
I have a button similar to below
<button id="uniqueId" onclick="runMethod(this)">Submit</button>
What I'm trying to do is stop the runMethod from running, until after I've done a check of my own. I've tried using the stopImmediatePropagation function, but this doesn't seem to have worked. Here's my jQuery:
$j(document).on('click', '#uniqueId', function(event) {
event.stopImmediatePropagation();
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Note: runMethod basically validates the form, then triggers a submit.
What you want to do, especially in the way that you want to do it, requires a some sort of workaround that will always be a bit fiddly. It is a better idea to change the way the button behaves (e.g. handle the whole of the click event on the inside of the jQuery click() function or something along those lines). However I have found sort of a solution for your problem, based on the assumption that your user will first hover over the button. I am sure you can extend that functionality to the keyboard's Tab event, but maybe it will not work perfectly for mobile devices' touch input. So, bear in mind the following solution is a semi-complete workaround for your problem:
$(document).ready(function(){
var methodToRun = "runMethod(this)"; // Store the value of the onclick attribute of your button.
var condition = false; // Suppose it is enabled at first.
$('#uniqueId').attr('onclick',null);
$('#uniqueId').hover(function(){
// Check your stuff here
condition = !condition; // This will change to both true and false as your hover in and out of the button.
console.log(condition); // Log the condition's value.
if(condition == true){
$('#uniqueId').attr('onclick',methodToRun); // Enable the button's event before the click.
}
},
function(){
console.log('inactive'); // When you stop hovering over the button, it will log this.
$('#uniqueId').attr('onclick',null); // Disable the on click event.
});
});
What this does is it uses the hover event to trigger your checking logic and when the user finally clicks on the button, the button is enabled if the logic was correct, otherwise it does not do anything. Try it live on this fiddle.
P.S.: Convert $ to $j as necessary to adapt this.
P.S.2: Use the Javascript console to check how the fiddle works as it will not change anything on the page by itself.
Your problem is the submit event, just make :
$('form').on('submit', function(e) {
e.preventDefault();
});
and it works. Don't bind the button click, only the submit form. By this way, you prevent to submit the form and the button needs to be type button:
<button type="button" .....>Submit</button>
Assuming there's a form that is submitted when button is clicked.
Try adding
event.cancelBubble();
Hence your code becomes:
$j(document).on('click', '#uniqueId', function(event) {
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Your code is mostly correct but you need to remove J:
$(document).on('click', '#uniqueId', function(event) {...
You also need to remove the onClick event from the inline code - there's no need to have it there when you're assigning it via jQuery.
<button id="uniqueId">Submit</button>
I have twp problems
Mark up for the link
DisplaySpreadsheetData
1)
Under document.ready i have this line of code to make sure the link is disabled by default but it does not work.
$('#displaySpreadSheetLink').bind('click', disableLink);
Code to disable the link
var disableLink = function (e) {
e.preventDefault();
return false;
}
2)
when the link is clicked i want to make sure that if checkFile() returns true the link should be disabled
$('#displaySpreadSheetLink').click(function (e) {
if (checkFile()) {
e.preventDefault();
}
});
There are two problems here. How can i correct the first problem and for the second one i think e.preventDefault() does not get executed even if checkFile() returns true.
Can anyone help please?
You might have an issue because you've actually bound two click events to your link. You should unbind the disableLink function before you bind the new functionality:
function disableLink(e) {
e.preventDefault();
// don't use return false here.
}
$(function() {
$('#displaySpreadSheetLink').click(disableLink);
});
// later on
$('#displaySpreadSheetLink').unbind('click').click(function (e) {
if (checkFile()) {
e.preventDefault();
}
});
Also, double-check your logic for checkFile(). Just based on the name I would assume, having never seen your code before, that you'd want to prevent the default behavior if checkFile() fails. Are you sure you don't want if (!checkFile()) { ... }?
Another approach might be to deal with only a single event, but take into account some extra state information as to whether the default behavior should execute or not:
(function($) {
var loaded = false;
$('#displaySpreadSheetLink').click(function(e) {
if (!loaded || checkFile()) {
e.preventDefault();
}
});
$(function() {
loaded = true;
});
})(jQuery);
Instead of disabling a link with a function after the page loads, you should change the HTML to be disabled initially by using a <span> with a CSS class that looks like a disabled link.
Instead of calling checkFile() every time the user clicks the link, have code in the sections that can alter whether checkFile() is true or false. For example, if checkFile() becomes true after a file is uploaded, put code in the file upload function to enable the link by replacing the <span> with an <a>, and link-disabling code in the appropriate places where checkFile() might become false again.
Merely using preventDefault() will make the link look clickable, which is probably bad UI design if it actually does nothing.
I have a button in my form. I need my form to be processed after the first click (or pressing Enter) on the button, and after that, if some conditions would be true, I do something like submitting the form by the second click or pressing Enter key on the button.
What do you think I have to do?
Create a (boolean) variable that saves your state, which is set to true when the first click (or action) has happened and your condition is true. Then submit on the second action when the variable is true.
If the condition has to be matched on both clicks (I guess so) consider the following:
$(function() {
var first = false;
$("form").submit(function() {
if(first && checkCondition())
submit();
if(!first && checkCondition())
first = true;
e.preventDefault();
});
});
so in basic code:
var answered = false;
$(function() {
$("form").submit(function() {
if(answered == false) {
answered = true;
return false;
}
});
});
If I've understood what you're trying to do correctly, you could bind an event handler to the submit event. That event handler will handle your validation, but if you use the jQuery one method, it will only be executed once. The next time the submit event is triggered, the form will submit as usual:
$("yourForm").one("submit", function(e) {
e.preventDefault(); //Stop the form from being submitted
//Do stuff
});
The result is effectively the same as #Manuel van Rijn's answer, but using jQuery's one just makes it a bit shorter and cleaner in my opinion. However, this could also add a slight performance benefit, as the event handler is unbound after it's execution and won't be called again.
I have a list of radio buttons that I can toggle "yes" or "no" to using Javascript.
$(document).ready(function(){
$('#select-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', true);
$('input[type="radio"]', this).eq(1).attr('checked', false);
});
});
$('#deselect-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', false);
$('input[type="radio"]', this).eq(1).attr('checked', true);
});
});
});
this works just fine. Now I have a separate piece of code that detects when a user has changed something, and asks them if they want to leave the page.
var stay_on_page;
window.onbeforeunload = confirm_exit;
$('.container form input[TYPE="SUBMIT"]').click(function(){
stay_on_page = false;
});
$('#wrapper #content .container.edit-user form').change(function(){
stay_on_page = true;
});
function confirm_exit()
{
if(stay_on_page){ return "Are you sure you want to navigate away without saving changes?"; }
}
The problem is that if the user uses the first piece of functionality to toggle all radio buttons one way or another. The JS detecting form changes doesn't see that the form was changed. I have tried using .live, but to no avail. Anyone have any ideas?
I do something similar to this by adding change() (or whatever's appropriate, click() in your case I suppose) event handlers which set either a visible or hidden field value, then check that value as part of your onbeforeunload function.
So, my on before unload looks like:
window.onbeforeunload = function () {
if ($('#dirtymark').length) {
return "You have unsaved changes.";
}
};
And, or course, dirtymark is added to the page (a red asterisk near the Save button), when the page becomes dirty.
<form method="post" action="/Order/CheckOut/" onSubmit="return Validate()">
and then...
function Validate() {
alert($("#email").val());
return false;
}
The messed up part is when I take out the alert it works fine, the submit fails, but when I put the alert in, it allows the submit to go through... what the heck?
I also tried this:
function Validate() {
if(document.getElementByID("email").value == "test"){
alert("It says test.");
}
return false;
}
and got the same behavior, it would never make it to the return statement...
If I step through the JS with firebug and break at the alert or the if (depending on the version above) it stops there, and I click 'step into' and it just submits the form, why isn't it making it to the return false line?
Why not wrap it in a try block?
function Validate() {
try {
alert($("#email").val());
} catch (e) {
alert("Problem: " + e);
}
return false;
}
You could use event.preventDefault() instead.
$("form[name='myForm']").submit(function(e){
e.preventDefault();
alert($("#email").val());
});
You should attempt to keep your javascript, css, and html all seperate. Don't integrate them, or you'll make the project more difficult to manage. Instead of using the onsubmit attribute in HTML, simply append your logic to the $.submit() method of the form from your javascript as I did above.
This example assumes that you've given your form a name of "myForm." I merely used this in the example as you should itendify which form you're handling the submit-event of, and not use a generic $("form") selector.
If you're already using jQuery you're doing the whole thing wrong to begin with. You shouldn't be manually specifying the onSubmit handler from within the <form> element. Do as #Jon suggested and just bind the submit event:
$("form").submit(function() {
alert($("#email").val());
return false;
});
The problem isn't that your function is returning true. The problem is that the JavaScript in the alert is failing and JavaScript quits interpreting the code. At which point, the browser is continuing with the default action which is to submit the form.
This is why Jonathan Sampson suggests using e.preventDefault() before the alert(), this way the browser doesn't continue with its default behaviour when the alert() fails.