Override inline click event in jQuery - javascript

I have links in a navigation that look similar to this
<a id="navform" href="#" tabindex="-1" onclick="mojarra.ab(this,event,'action','#form','content');return false" class="active"><span>Policy</span></a>
I am checking for form changes and trying to disable the onclick event for the links when there are changes and enable them if once the user saves the form.
$(':input').on('change', function() {
formChanged = true;
});
$('nav a').on('click', function(e){
if(formChanged){
e.preventDefault();
$(this)[0].onclick = null;
}
});
I have tried preventDefault and nulling the event according to some answers I found on here, but no luck. Could someone please tell me how to fix this?
UPDATE:
Thanks to all your answers, I got some ideas and figured how to fix it:
if($('.policy-form')){
$(':input').on('change', function() {
formChanged = true;
$('nav a').each(function(){
var handler = $(this).attr('onclick');
$(this).removeAttr('onclick');
$(this).on('click',function(){
if(formChanged){
invokeDialog("warning");
formChanged = false;
$(this).attr('onclick', handler);
}
});
});
});

Plain JavaScript one-liner
Use
document.getElementById('navform').onclick = null;
This is because only the last onclick defined will run and here we override it with null.
Note that it would be way better if you would just avoid onclick in your HTML, or if you would at least modify mojarra.ab() appropriately, so that it performs any actual actions only when you desire.
Demo:
document.getElementById('one').onclick = null;
<a id="one" href="#" onclick="alert(true)">Doesn't alerts</a>
<br/>
<a id="two" href="#" onclick="alert(true)">Does alerts</a>
EDIT
Vide comment, here is an example of toggling old onclick on and off:
var button = document.getElementById('button');
var oldOnclick = button.onclick;
document.getElementById('toggle').addEventListener('click', function() {
button.onclick = button.onclick !== null ? null : oldOnclick;
})
<input id="button" type="button" onclick="alert('Test')" value="Alert"/>
<br/>
<br/>
<input id="toggle" type="button" value="Toggle above button"/>

$('nav a').on('click', function(e){
$(this).removeAttr('onclick'); // add this line to remove inline onclick
if(formChanged){
e.preventDefault();
$(this)[0].onclick = null;
}
});

You can use the .off() method:
$('nav a').off('click');
One good practive is to add an namespace to your events.
$('nav a').on('click.somenamespacehere', function(e){
});
...
$('nav a').off('click.somenamespacehere');
In this case, you can specify later which events you want to remove (with the off method)

You can't do it that way because the on('click' event and the inline one are two different events and there's no way to tell which would happen first. But, you could replace the inline handlers with your own handler like so
on('click', function(e) {
if (formChanged) {
mojarra.ab(...);
}
});

With an inline click function there are many possibilities to control the logical flow or order of executing the functions attached to the same event.
One possibility is to change the inline code so that you can define a first function and based of the result of this you may decide if execute or not the next function.
My snippet:
// assuming the inline onclick function is like:
function mojarra_ab(_this, event, _action, _form, _content) {
$('<p>Executed function: mojarra_ab</p>').appendTo('body');
}
function myNewClick() {
$('<p>Executed function: myNewClick</p>').appendTo('body');
if ($('#yesNo option:selected').val() == 'true') {
return true; // return true to execute the mojarra_ab function
}
return false; // return false if you don't need to execute the mojarra_ab function
}
$(function () {
$('nav a').attr('onclick', function(index, attr) {
return 'if (myNewClick() == true) {' + attr + '}';
});
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
Choose if to run myNewClick and then mojarra_ab: <select id="yesNo">
<option value="true" selected>True</option>
<option value="false">False</option>
</select>
<nav>
<a id="navform" href="#" tabindex="-1" onclick="mojarra_ab(this,event,'action','#form','content');return false"
class="active"><span>Policy</span></a>
</nav>

Related

I want to call two functions from one onclick [duplicate]

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :)
However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
The HTML
click
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
There is no need to have two functions within one element, you need just one that calls the other two!
HTML
<a href="#" onclick="my_func()" >click</a>
JavaScript
function my_func() {
my_func_1();
my_func_2();
}
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

Function gets called twice for each click

The $(".actionsAdListnTo").click function is getting fired twice.
I tried various solutions posted in StackOverflow but nothing worked.
What is the reason of twice firing any pointers please.
How to avoid this?
$(".actionsAdListnTo").click(function (e) {
$('#actionsAdListnTo').slideToggle();
});
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
var ddlselectedVal = $(this).attr('id');
var $form = $("#frmPostToEmailReports");
var selectedListinsCount = selected_Listings.length;
var SelectedMlsnums = selected_Listings.join();
if (ddlselectedVal != "None" && ddlselectedVal != "select") {
//*********** To Cart Functionality
if (ddlselectedVal == 'Tocart') {
if (selectedListinsCount > 500) {
if ($('#errmesg').length == 0) {
$('.messageCenter').append('<span id="errmesg" class ="errmesg"> <span class="messageIcon"></span><span>The maximum number of listings you may select To Add to cart is 500.</span></span>');
return false;
}
} else {
$.post(urlstring,
function (data) {
$(window.open(urlstring, '_blank', 'width=750, height=400')).load(function (e) {
var $formCopy = $("#frmPostToEmailReports").clone();
$($formCopy).append('<input id="SelectedMlsnums" name="SelectedMlsnums" type="hidden" value="' + SelectedMlsnums + '">');
// Here "this" will be the popup window. insert a form element into the popup window.
$(this.document).find("#divfrmInfo").html($formCopy);
e.preventDefault();
});
});
}
}
}
});
HTML :
<div class="actionsAdListnTo">
<span> Add Listing To</span>
<ul id="actionsAdListnTo" class="ddlAddListinTo" style="display: block;">
<li id="Tocart">To CART</li>
<li id="Toportal">To Portal</li>
<li id="SaveListings">Save Listing</li>
</ul>
</div>
The click on li bubbles to its parents, one of them being <div class="actionsAdListnTo">, so the parent's click handler is also called. Try to stop propagation of the click on li:
$(".ddlAddListinTo li").click(function (e) {
e.stopPropagation();
...
In this case it looks it would be more correct to target the link only for the toggle and not the outer div. Be as specific with your selectors as possibe, similar to this:
$(".actionsAdListnTo a#select").click(function (e) {
$('#actionsAdListnTo').slideToggle();
});
If you want to be more specific without an id using the structure, you could do it simlar to:
$(".actionsAdListnTo > span:first > a").click(function (e) {
$('#actionsAdListnTo').slideToggle();
});
Anyway, the way your HTML is structured there is no need to have the toggle triggered by the div as only the link should react to it.
DEMO - Getting more specific with the selector
What I see here is that you are defining two events in the same place, the second one on a child.
$(".actionsAdListnTo").click( function(e){
...
});
$(".ddlAddListinTo li").click(function () {
...
})
Maybe you can use e.sTopPropagation() in the second one, or e.preventDefault()

How can i prevent double submission of <a href="">?

I have a question regarding the double submission.
I have a multiple <a href = "">.
I want to disables all the <a href=""> if i click in one of the <a href= "">
Code:
<a href="dashboard.php" id ="submitID" class="submit" >Dashboard </a>
<a href="orderList.php" id ="submitID" class="submit" >Order List</a>
New Order
First, please fix your ids to be unique.
If you're using jQuery versions 1.4.3+:
$("a.submit").click(function() {
$("a.submit").bind('click', false);
});
If not, bind function() { return false; }. Then you can also
$("a.submit").unbind('click')
when you want them to work again.
Welcome to Stack Overflow.
First of all, you should never have multiple DOM elements with the same ID.
Second of all, set a variable in a bind to the submit class (the bind is using jquery), and flip it if you submit.
Include jquery with a script tag and then wrap your javascript in document ready
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript>
$(document).ready(function () {
$('.submit').bind('click', function () {
var isSubmitted = false;
if (isSubmitted === false) {
$.get($(this).attr('href'), function () {
isSubmitted = true;
});
}
});
});
</script>
This is of course assuming you want some ajax style functionality. If not, you shouldn't really be worried if you have a link since you'd be posting to a new page
Jquery:
var count=0;
$(".submit").click(function(){
if(count>0){
return false
}
++count;
});
HTML
<a href="dashboard.php" id ="submitID1" class="submit" >Dashboard </a>
<a href="orderList.php" id ="submitID2" class="submit" >Order List</a>
New Order
var submitStatus = false;
$('a.submit').click(function(e){
if (!submitStatus) {
alert('clicked');
submitStatus = true;
} else {
e.preventDefault();
}
});
You can try it here: http://jsfiddle.net/p8a5s/
And dont use the same IDs for different DOM elements, of course

Disable image link on click

I have a image that links to a page. This is a process button which can take up to 20 seconds to run.
I want to prevent the user from pushing it more than once.
How would I write a Javascript that when the button is pushed, it would follow the hyperlink, but the link for the button would disable, and the image would change?
<script>
function buttonClicked()
{
document.getElementById('buttonImage').src = 'new-image.jpg';
document.getElementById('buttonId').disabled = true;
}
</script>
<a id="buttonId" href="next-page.html" onclick="return buttonClicked()"><img id="buttonImage" src="image1.jpg"></a>
From your question, it sounds like your "button" is the image that you click on...if that's true then you can use the following:
<a id="my_link" href="/page_to_vist_onclick"><img id="my_image"></a>
Then your javascript would be:
document.getElementById('my_link').onclick = function() {
document.getElementById('my_link').disabled = true;
document.getElementById("my_image").src='the_path_to_another_image';
};
On click, remove the href attribute from the a element.
I ended up going with the following:
$(document).ready(function() {
var isSubmitted = false;
$("#submit").click(function(e) {
if ( ! isSubmitted ) {
isSubmitted = true;
var src = $(this).attr("src").replace("gold","red");
$(this).attr("src", src);
} else {
e.preventDefault();
}
});
});
Here is a really simple one for you
in your JS
function Create(){
document.write('<INPUT disabled TYPE="button" value="Click Me!">');
}
in your HTML
<INPUT TYPE="button" value="Click Me!" onclick="Create()">
If you are ready to use jQuery, then here is another solution.
$("selectorbyclassorbyIDorbyName").click(function () {
$("selectorbyclassorbyIDorbyName").attr("disabled", true).delay(2000).attr("disabled", false);
});
select the button and by its id or text or class ... it just disables after 1st click and enables after 20 Milli sec
Works very well for post backs n place it in Master page, applies to all buttons without calling implicitly like onclientClick
you can use this.
<script>
function hideme()
{
$("#buttonImage").hide();
}
</script>
<a id="buttonId" href="next-page.html" onclick="return hideme()"><img id="buttonImage" src="image1.jpg"></a>
if you don't want to hide image please use this..
$('#buttonImage').click(function(e) {
e.preventDefault();
//do other stuff when a click happens
});
That will prevent the default behaviour of a hyperlink, which is to visit the specified href.
Let's make a jquery plugin :
$.fn.onlyoneclick=function(o){
var options=$.extend({src:"#"},o);
$(this).click(function(evt){
var $elf=$(this);
if( $elf.data("submitted") ){
evt.preventDefault();
return false;
}
$elf.attr("src", typeof(options.src) == 'function' ?
options.src($elf.attr("src"))
: options.src
).data("submitted",true);
});
}
$(".onlyoneclick").onlyoneclick({
src : function( src ){
return src.replace("gold","red");
}
})
on any button that should trigger only once :
<button ... class="onlyoneclick">tatatata... </button>
its simple...just one line of code :)
Onclick return false.

Can I have two JavaScript onclick events in one element?

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :)
However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
The HTML
click
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
There is no need to have two functions within one element, you need just one that calls the other two!
HTML
<a href="#" onclick="my_func()" >click</a>
JavaScript
function my_func() {
my_func_1();
my_func_2();
}
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

Categories