I am wondering if someone can help me out with this.
I have a button defined as:
<input type="button" id="myButton" name="myButton" value="ClickMe!!" onClick="callMe()"/>
I can use jQuery, standard javascript or Dojo to disable the button with onClick event:
$('#myButton').attr('disabled', 'disabled');
The problem I am facing is, even though this code disables the button, onClick event still triggers the function callMe() if I click on the button.
How do I make the disabled button not call the onClick function?
With jQuery you can bind a function that checks if your button is disabled:
$('#myButton').click(function() {
if (!$(this).is(':disabled')) {
callMe();
}
});
Since you're using jQuery, use
$('#myButton').click(function() { callMe(); this.unbind(); });
instead of onClick.
$('#myButton').click(function(){
if( !$(this).is('[disabled=disabled]') ){
...
}
});
In the same code where you disable it, simply remove the onclick event handler.
instead of using onclick attribute, bind to the event
$('#myButton').click(function(e){
// try it without this
if($(this).attr('disabled'))
return false;
callMe();
e.preventDefault();
});
try it without the check, not sure if its necessary.
This is one way of doing.
$('#myButton').click(function(){
if(!$(this).hasClass("disabled")){
//Do stuff here
}
});
To disable the buttons just add the disabled class to it.
$('#myButton').addClass("disabled");
Add appropriate styles in the disabled class to make button look like disabled or you can also set the disabled property along with setting the class.
you should be using jQuery to attach the click handlers, not adding them inline*
Just add a check to your click function
$('#myButton').click(function(){
var $this;
$this = $(this);
if ( $this.is(':disabled') ) return;
callMe();
});
Alternatively,
$('#myButton').click(callMe);
callMe()
{
var $this;
$this = $(this);
if ($this.is(':disabled')) return;
...the rest of your code...
}
Or if you insist on using it inline:
onclick="if ($(this).is(':disabled')) return; callMe();"
* I regularly rant about how HTML, CSS & JS fit the definition of MVC
Instead of ...
$('#myButton').attr('disabled', 'disabled');
... use ...
$('#myButton')
.prop('disabled', 'disabled') // Sets 'disabled' property
.prop('onclick', null) // Removes 'onclick' property if found
.off('click'); // Removes other events if found
Related
I have a checkbox and I marked it as checked, however it doesnt fire the on change function. The note doesn't appear.
My code:
$('#checkbox1').prop("checked", true);
$('#checkbox1').change(function(){
if ($(this).is(':checked'))
$('#s-note').show();
else
$('#s-note').hide();
});
Do you expect the onchange to fire without user interaction?
Your issue is you set the checked state before you set the handler so if this would have trigged change, you would have not caught it. Your real issue here is setting the property with JavaScript does not fire the change event. So you need to trigger the change event manually.
$('#checkbox1')
.prop("checked", true) // set it to checked
.on("change", function() { // bind change event
$('#s-note').toggle($(this).is(':checked')); // toggle visibility
}).trigger("change"); //trigger that you need the change to run
If you are setting the note to be hidden by default and doing it with an id based selector, like this:
#s-note { display:none; }
Then your code won't be able to show it because it also uses an id based selector and that won't be more specific than the selector already in effect.
Instead, you'll have to default the note to hidden using a selector that is less specific than the id selector you will use to show/hide it later. That would be a class.
Also, it's critical that you set up the event handler before you trigger the event, so that when the event happens, there is already an event handler registered.
Now, for your needs, you don't really need the change event, click will do just fine. And, lastly, to ensure that you properly trigger the event, use JQuery's .trigger() method to set things in motion.
// Make sure you set up the callback first
$('#checkbox1').on("click", function(){
if ($(this).is(":checked"))
$('#s-note').show();
else
$('#s-note').hide();
});
// Then just trigger the event
$('#checkbox1').trigger("click");
.hide { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1">Test
<div id="s-note" class="hide">Special</div>
I hope this code snippet will help you
Approach 1
$('#idcheckbox').on('change', function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('default ');
}
});
Approach 2
$('input[type=checkbox]').on('change', function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('default ');
}
});
I ran your code in .net mvc and it runs fine.
This is the checkbox same id it hide or shows div element.
<input type="checkbox" id="checkbox1" value=" " />
<div id="s-note" style="display: none">
<label>Showing</label>
</div>
What are you trying to display?
I was wondering if Javascript or jQuery have a way to delete an event listener. Let's say I want to make a function that I want to trigger only once, for example let's say I want to have a button that shows some hidden elements on the document, I would make this function (assuming the hidden elements have a hidden class that hides them):
jQuery('#toggler').click(function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
});
Simple enough, right ? Now, my actual problem comes in, I don't want jquery to run that function again and again each time the button is clicked, because the elements are already revealed, so is there a clean way to do it ? So, in this example after clicking the toggler multiple times I want to get only one console message.
I could do jQuery(this).unbind('click'), but this results into removing ALL triggers and I only want to remove the current trigger.
What I usually do when I face such scenarios is solve it like this (which is ugly and doesn't actually prevent code execution, but only handles the code's results) :
var toggler_clicked = false;
jQuery('#toggler').click(function() {
if(toggler_clicked) return;
toggler_clicked = true;
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
});
Also I don't want to use jQuery's one, because I will have the same problem when I'll need to delete the trigger conditionally, so if you can help please give me a dynamic answer.
Thanks in advance !
You have to name your function like that:
var myFunction = function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
};
And bind it this way
jQuery('#toggler').click(myFunction);
Then you can unbind it with :
jQuery('#toggler').off('click',myFunction);
Without unbinding the other listeners
You can try this:
var myFunc = function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
jQuery(this).unbind('click', myFunc);
};
jQuery('#toggler').click(myFunc);
This way of calling unbind is such that only the listener for myFunc handler is removed and not all the events connected to the click on the toggler.
I would use the .on() and its opposite .off() methods to attach/detach the event handler. It is the recommended way since 1.7 instead of the .bind() and .unbind() versions that became deprecated as of jQuery 3.0.
$("#toggler").on("click", function(event) {
console.log('Hidden elements are now shown');
$('.hidden').removeClass('hidden');
// if (/* Add your condition here */) {
$(this).off(event);
// }
});
$("#toggler").on("click", function(event) {
console.log('Hidden elements are now shown');
$('.hidden').removeClass('hidden');
// if (/* Add your condition here */) {
$(this).off(event);
// }
});
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggler">Toggle</button>
<div class="hidden">
HIDDEN
</div>
Try this
var myFunction = function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
};
Add the event listener like this:
jQuery('#toggler').addEventListener("click", myFunction);
And remove it like this:
jQuery('#toggler').removeEventListener("click", myFunction);
So all together this will do the trick:
var myFunction = function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
jQuery('#toggler').removeEventListener("click", myFunction);
};
jQuery('#toggler').addEventListener("click", myFunction);
more about the HTML DOM removeEventListener() Method
Jquery unbind function takes 2 parameters eventType and handler
You can put your event listener into separate function like this:
var clickEventHandler = function(){
//your logic goes here
}
After you add listener as reference:
jQuery('#toggler').click(clickEventHandler);
And then, later, anytime, anywhere you want you can unbind that specific handler:
jQuery('#toggler').unbind('click', clickEventHandler);
What i used to do in the past is toggle the click behavior using css classes, ex i used to set a click listener on the parent and delegate to all of the children something that jquery is doing now by default i believe. Anyway based on the css class it will trigger an event for ex.
$('.some-parent-element').on(
'click',
'the-behavior-css-class',
function() { // do stuff here.... }
)
Now if you want to remove this behavior you can just toggle the class of the element and it should do the job. ex
$('.some-parent-element').on(
'click',
'hide-me-on-click-or-whatever',
function() {
$(this).toggleClass('hide-me-on-click-or-whatever')
// perform the action
}
)
You can check if the element has the class hidden
After initialize js I create new <div> element with close class and on("click") function doesn't work.
$(document).on('click', '.post-close', function () {
alert("hello");
});
but on('hover') work perfectly.
$(document).on('hover', '.post-close', function () {
alert("hello");
});
but I need to make it work on click.
It's because you're not preventing the default behaviour of the browser. Pass e into your handler and then use e.preventDefault()
$(document).on('click', '.post-close', function (e) {
e.preventDefault();
alert("hello");
});
Edit
Also, bind the handler before creating the new <div>
why not use something like
$('.post-close').click(function(){
//do something
});
If the element was added dynamically use:
$(document).on('click', '.post-close', function(){
//do something
});
edit:
like danWellman said, you can add the preventDefault IF you want to make sure no other code is executed. otherwise use the code above.
edit2:
changed the .live to .on
It's an old post but I've had a exactly same problem (element created dynamically, hover works, but click doesn't) and found solution.
I hope this post helps someone.
In my case, I found ui-selectable is used for parent element and that was preventing from click event propagate to the document.
So I added a selector of the button element to ui-selectable's 'cancel' option and problem solved.
If you have a similar probrem, check this
Try turn of libraries for parent element
You're not using stopPropagation() in parent element ?
Im trying to build a tabbed content box, and im wondering if its possible that i can disable 1 link with a specific class, such as 'disabled'
I read somewhere about a function called preventDefault, would this work?
http://jsfiddle.net/Ssr5W/
You can disable click event by returning false. like,
$('#tabmenu a').click(function() {
return !$(this).hasClass('disabled');
});
Also, I've updated your fiddle: http://jsfiddle.net/Ssr5W/1/
EDITED
and of course, preventDefault would work :)
$('#tabmenu a').click(function(e) {
if($(this).hasClass('disabled'))
e.preventDefault();
});
fiddle: http://jsfiddle.net/Ssr5W/2/
$('.disabled').click(function(e) {
e.preventDefault() ;
}) ;
You can just check for the class on the element that was clicked on:
$('tabElement').click(function(){
if(this.hasClass('disabled'))
return;
//Your code here..
);
This won't interfere with other clikc-handlers you may have on your tab element
I am trying to add an onClick event to an anchor tag ...
Previously i had ...
<a href="somlink.html" onClick="pageTracker._link(this.href); return false;">
But i am trying to avoid the inline onClick event because it interferes with another script..
So using jQuery i am trying the following code ...
<script>
$(document).ready(function() {
$('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
pageTracker._link(this.href);
return false;
});
});
</script>
with the html like so <a id="tracked" href="something.html">
So my question is should this be working, and if not what would be the best solution?
The correct way would be (as for jQuery)
$('#tracked').click(function() {
pageTracker._link($(this).attr('href'));
return false;
});
This will add an "onclick" event on any element with tracked id. There you can do anything you want. After the click event happens, the first line will pass href attribute of the clicked element to pageTracker.
As for your original question, it wouldnt work, it will raise undefined error. The attr works a bit different. See documentation . The way you used it, would return the value of the attribute and I think that in that case its not chainable. If you would like to keep it the way you had it, it should look like this:
$('#tracked').click(function() {
$(this).attr('onclick', 'pageTracker._link(this.href); return false;');
return false;
});
You can also try
var element1= document.getElementById("elementId");
and then
element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");
// here i am trying to set the onchange event of element1(a dropdown) to redirect to a function()
I spent some time on this yesterday. It turned out that I needed to include the jQuery on $(window).ready not $(document).ready.
$( window ).ready(function() {
$('#containerDiv a').click(function() {
dataLayer.push({
'event': 'trackEvent',
'gtmCategory': 'importantLinkSimilarProperties',
'gtmAction': 'Click',
'gtmLabel': $(this).attr('href')
});
});
});