button onclick function is unnecessarily reloading the page after the function execution - javascript

Here is a button onclick which calls a function. When this button is clicked after the function execution, the page is getting reloaded in firefox browser.
<button id="next" class="submit" type="submit" onclick="onNextEvent()" return false;>Next</button>
When
event.stopImmediatePropagation();
event.preventDefault();
are removed from this
function, the page is getting reloaded in Chrome browser.I am using Jquery jquery - 1.9.1.js.Please help!Thanks
function onNextEvent() {
event.stopImmediatePropagation();
event.preventDefault();
if ($('.current').hasClass('first')) {
$('.current').removeClass('current').hide()
.next().show().addClass('current');
$('#prev').show();
$('#prev').attr('disabled', null);
$('#skip').show();
return;
}
}

Try this:
function onNextEvent(event)
{
event.preventDefault();
/* Rest of code */
Or
function onNextEvent(event)
{
event.stopImmediatePropagation();
/* Rest of code */

The return false statement should be implemented together with the onclick like this:
<button onclick="onNextEvent(); return false;">
Or, the function called can return false:
function onNextEvent() {
//function code
return false;
}
I have used the first way several times and it always worked for me.

Related

jquery javascript click function from within a function

I have an external JS file that contains the following jQuery code:
var globalNames = { next: 'input[name="next"]'};
var globalElements = { next: $e.find(globalNames.next) };
initQuiz: function() {
globalElements.next.click(function () {
if (y.forcingQuestionSolve && !j[c.index()] && (y.quizSummeryHide || !y.reviewQustion)) {
alert(WpProQuizGlobal.questionNotSolved);
return false
}
i.methode.nextQuestion()
}
);
the globalElements.next.click function is triggered by a click on a button:
<input type="button" name="next" value="Next" class="Button" ">
What I would like to do is call this p.next.click function from a Input Checkbox click.
I have added the following code:
<script>
$(document).on("click", "input[class='questionInput']", function () {
alert("Thanks for checking me");
// This is the line I'm not sure off !?!?
$('next').trigger('click');
});
</script>
As you can see, I have tried to call the trigger event but its not working.
I have to note that the 2 jQuery statements are not combined in document, they are separate.
EDIT: Added Correct Variables (global*)
Hi i think you only forgot to dedicate the button which has to be triggered.
<script>
$(document).on("click", "input[class='questionInput']", function () {
alert("Thanks for checking me");
// This is the line I'm not sure off !?!?
$('[name=next]').trigger('click');
// $('.Button').trigger('click');
});
thanks everyone.. I used the following code from Calvin Nunes-
$("[name='next']").trigger('click');
Craig.

How to make onclick to fire when javascript returns false

The onclick doesn't work when the javascript returns false. I need javascript to return false in order to animate the button. If I return true then the onClick works but the animation doesn't work. I have tried doing __doPostBack and UseSubmitBehaviour but nothing seems to work. Any help would be really appreciated on how to fix this.
Code for asp button:
<asp:LinkButton id="btn_salaries" onClientClick="return fncsave();" OnClick="btn_clicked" UseSubmitBehavior="false" runat="server" type="button" class="list-group-item" Text="getCharitySalaries"/>
Javascript code:
function fncsave(){
$(document).ready(function(){
$("#list").click(function(){
$("#list_of_btns").animate({left: '-290px'});
});
});
return false;
}
Update:
I'm doing the animation in ajax but I don't know if I'm doing this correctly because it does not perform the animation.
This is my code below:
function fncsave(){
alert("dsfdsf");
$(document).ready(function(){
$(document).ajaxStart(function(){
$("#list_of_btns").animate({left: '-290px'});
}
}
return true;
}
You should not check for document ready event on the click event handler. Also, when someone clicks on the link you are calling fncsave function but inside that function you are subscribing to another event (click) on the tag with id list.
If I understand correctly, you should do this:
function fncsave(){
$("#list_of_btns").animate({left: '-290px'});
return false;
}
Just as a comment, "return false" means that it's not gonna continue with the normal flow of the event handling, which is submit the form.
If you return true, the form is submitted. That means the form data is sent to the server and the C# code is executed. Then, the page if fully reloaded (from scratch). In that case, the animation makes no sense and you'll need AJAX to perform an animation while the C# code is running. See this tutorial about AJAX (Tutorial about AJAX).
Try like this
function fncsave(){
$("#list").click(function(){
$("#list_of_btns").animate({left: '-290px'},900,function(){
return false;
});
});
}
I have a 'animated' variable with default is false. If button is clicked, check if animated is false, 'preventDefault()' cancel the submit, play animation, 'setTimeOut()' will the function after 3000ms, assign animated to true, and trigger 'click' on the button. This time, animated is true and it post data to server.
<asp:Button ID="btn_salaries" OnClick="Button_Click" runat="server" type="button" Text="getCharitySalaries" />
<br />
<script type="text/javascript">
$(document).ready(function (e) {
var animated = false;
$('#' + '<% = btn_salaries.ClientID %>').click(function (ev) {
if (!animated) {
ev.preventDefault();
$(this).animate({ left: '-290px' });
setTimeout(function () {
animated = true;
$('#' + '<% = btn_salaries.ClientID %>').trigger('click');
}, 3000);
}
});
});
</script>
Hope this help.
This should do what you want.
function fncsave(){
$("#list_of_btns").animate({left: '-290px'},900,function(){
// Do __doPostBack here
});
return false;
}
It'll delay doing the post back until after the animation is done. An alternative would be to use update panels to avoid the flicker from the post back that'll follow the animation.

Using click event while button is disabled

I need to check on clicks while the button is disabled is this possible? Or is there any other way to this?
HTML:
<form id="form">
<input type="submit" id="submit" value="Submit" />
</form>
JS:
$("#form").submit(function (e) {
e.preventDefault();
return false;
$("#submit").on("click", function () {
alert("Bla");
});
});
JS Fiddle: http://jsfiddle.net/hjYeR/1/
When you are using preventDefault(), there is no need to use return false.
However, any code after return statement in a function, won't execute.
Also there is no need to attach an event inside another event, write them separately:
$("#form").submit(function (e) {
e.preventDefault();
});
$("#submit").on("click", function () {
alert("Bla");
});
jsFiddle Demo
After you return false; the rest of your function will not run. You can bind your click event before returning false and it should work.
return statements are the end point in the function, the codes will not proceed ahead of that.
What you can do is simply remove the click event handler from within the submit handler itself.
$("#form").submit(function (e) {
return false; //e.preventDefault(); is not needed when used return false;
});
$("#submit").on("click", function () {
alert("Bla");
});

Calling JS functions from Href

I'm curious whats the best way to call a JS function with a href link in HTML. I don't use a library and i see alot of mention about jquery using event handlers ...
But if im not using a library can it still be done or will i have to use an on click type call ?
You can use event handlers with plain javascript. No framework is required. Here's a cross browser function I use:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
And, an example of using it would be like this:
HTML:
<a id="myLink" href="#">Click ME</a>
Javascript:
var link = document.getElementById("myLink").
addEvent(link, "click", function(e) {
// process the click on the link here
});
If you don't want the default click of a link to happen, then you need to prevent the default behavior from the event handler like this:
var link = document.getElementById("myLink").
addEvent(link, "click", function(e) {
// process the click on the link here
// prevent default action of the click
if (e.preventDefault) {
e.preventDefault(); // normal browsers
} else {
e.returnValue = false; // older versions of IE (yuck)
}
});
try this
function test() { alert (''); }
<a href="#" onclick="test();" />
Basically there are two ways:
...
and
...
(in this case someFunction must return false)
I prefer the latter.

Upon Link Click and setTimeout

In JavaScript, I am trying to execute a function 2 seconds after a link is clicked, and wait until the function completes its execution before going to the link destination.
/* JavaScript */
function myFunction() { /* Block of code, with no 'return false'. */ }
<!-- HTML -->
<a onclick="setTimeout(myFunction, 2000);" href="http://www.siku-siku.com">Link</a>
The problem is upon click, the browser immediately goes to the link destination i.e. myFunction didn't have time to execute. Did I miss anything here?
Thanks beforehand.
You will need to return false from your onclick event, to cancel the actual browser handled page load.
And since you want to follow the link (once the function is complete) you will need to do that through javascript. But you are using a timeout so you loose the reference to the clicked element, so we need to pass that too in the method (if you want this logic for multiple links)
html
<a onclick="return createTimedLink(this, myFunction, 2000);" href="http://www.siku-siku.com">Link</a>
javascript
function createTimedLink(element, callback, timeout){
setTimeout( function(){callback(element);}, timeout);
return false;
}
function myFunction(element) {
/* Block of code, with no 'return false'. */
window.location = element.href;
}
demo at http://jsfiddle.net/gaby/mdkjX/2/
<a onclick="setTimeout(myFunction, 2000);" href="#">Link</a>
JAVASCRIPT
function myFunction(){
////your other code
///
///
window.location="http://www.siku-siku.com";//at the end
}
demo here
Yes, the default behavior for a link is a GET request sent by the browser. Imagine that before you register your handler, browser has registered another handler to initiate a get request (just imaginary). This is the case here. You should return false in your inline handler:
onclick = '(function(){ setTimeout(yourFunction, 2000); return false;})()'
or more simpler:
onclick = 'setTimeout(yourfunction, 2000); return false;'
Update:
Use this (it requires jQuery):
$(function () {
$('a').click(function (e) {
e.preventDefault();
var target = $(this).attr('href');
setTimeout('go("' + target + '")', 2000);
});
});
function go(target) {
console.log('2 seconds passed');
document.location = target;
}

Categories