jQuery: Disable onclick event using off() not working - javascript

Here is a simple example of what I'm trying to do, I have code in HTML and my aim is to disable the three hyperlinks #validate,#organize and #export:
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >>
<a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
</p>
When I'm trying to call the following, nothing happend. I'm using jQuery 1.11.4 and I've read that the methods for disabling event listeners have changed since 1.7. So I would like to know if there is an error in my JavaScript code below or some new changes:
$('#validate').off('click');
$('#organize').off('click');
$('#export').off('click');

One way would be to temporarily set the onclick to null, but store the original element onclick in the element or jquery object (e.g. data). With a helper function you can switch the elements on or off:
function setEnabled($a, Enabled ){
$a.each(function(i, a){
var en = a.onclick !== null;
if(en == Enabled)return;
if(Enabled){
a.onclick = $(a).data('orgClick');
}
else
{
$(a).data('orgClick',a.onclick);
a.onclick = null;
}
});
}
Which can be called with something like:
setEnabled($('#validate'), false);
(also works on jquery objects with multiple elements because of the each)
Example fiddle

You need to unbind the click event (which was declared inline) as follows.
document.getElementById("import").onclick = null;
document.getElementById("validate").onclick = null;
document.getElementById("organize").onclick = null;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >>
<a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
</p>

You could have jQuery take over your inline event, so that you can off() it later. Note that off() does remove the listener. You can't really disable it unless you put some logic in the handler itself to bail out if it shouldn't be running.
function switchScreen(screenName) {
console.log(screenName);
};
$(function() {
$('#menuitems a').each(function() {
var oldClick = this.onclick;
$(this).on('click', $.proxy(oldClick, this));
this.onclick = null;
});
$('#import').off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >>
<a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
</p>

try unbind instead of Off since click event is defined inline, if click is attached using on then it will work with off.

Event attached through javascript doesn't recognize by jquery, so javascript and jquery mixed approached can't work properly - that's the reason jquery
.off('click'); doesn't detach click event.
Modify html:
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);">IMPORT</a> >>
<a id="validate" href="javascript:void(0);">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);">EXPORT</a>
</p>
Attach click event using jquery:
$(document).ready(function () {
$('#import').on("click", function () {
switchScreen('Import');
});
$('#validate').on("click", function () {
switchScreen('Validate');
});
$('#organize').on("click", function () {
switchScreen('Organize');
});
$('#export').on("click", function () {
switchScreen('Export');
});
});
Disable click event whenever required:
$('#import').off('click');
$('#validate').off('click');
$('#organize').off('click');
$('#export').off('click');
The above approach works for all standard browsers but just for IE we can have one more approach:
$('#validate').attr("disabled", "disabled");
$('#organize').attr("disabled", "disabled");
$('#export').attr("disabled", "disabled");

Related

Disable selected anchor button on click in foreach loop

In my laravel application foreachloop rendring multiple button i want that disable or remove only that button which is clicked so i tired this piece of code
#foreach()
<a onclick="remvebtn()" class="btn">My Button</a>
#endforeach
javascript
function remvebtn(){
$(this).removeAttr("onclick");
}
but it is not helpful
Here is a very simple way of removing the onclick event from a button, once it is clicked:
function remvebtn(btn){
console.log(btn.textContent)
btn.onclick=null;
}
<a onclick="remvebtn(this)" class="btn">My Button1</a><br>
<a onclick="remvebtn(this)" class="btn">My Button2</a><br>
<a onclick="remvebtn(this)" class="btn">My Button3</a><br>
<a onclick="remvebtn(this)" class="btn">My Button4</a>
Or, you can also do it like this:
document.body.onclick=ev=>{
let btn=ev.target;
if (btn.classList.contains("btn")){
ev.preventDefault();
console.log(ev.target.href);
btn.classList.remove("btn");
btn.removeAttribute("href");
}
}
My Button1<br>
My Button2<br>
My Button3<br>
My Button4

Turn Inline OnClick to Click Jquery

I have the following inline styles for a dropdown menu list. I do not know how to make it in to 'click' using jQuery.
<button class="btn btn-primary mw" data-toggle="dropdown"><span class="caret">Subject</span></button>
<div class="dropdown-menu">
<a class="dropdown-item Business" onclick="selectBusiness()"> Business</a>
<a class="dropdown-item ICT" onclick="selectICT()"> ICT</a>
<a class="dropdown-item Arts" onclick="selectArts()"> Arts</a>
</div>
More information:
I tried to do this following code for a button and it's working fine. But as I said I do not know how to make it work for a dropdown menu.
var btn = document.querySelector("button.selectAll");
btn.addEventListener("click", selectAll);
....
Your input would be greatly appreciated!
If you want to use jQuery, you can add listener to the classes of each <a> inside your dropdown.
$(".Business").on('click', function() {
//selectBusiness() or your code here
});
$(".Arts").on('click', function() {
//selectarts() or your code here
});
$(".ICT").on('click', function() {
//selectICT() or your code here
});
Another solution would be to add a single listener for all your dropdown-items and then checking the content of the selected one.
$(".dropdown-item").on('click', function() {
switch ($(this).text()) {
case "Business":
selectBusiness();
break;
}
});

jquery script doesn't work for me

$('a.locked').click(function(e) {
e.preventDefault();
});
$(document).ready(function(){
$("button.button2").click(function(){
$("a").removeClass("locked");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="example.com"target="_blank" id="action2">
<button class="button2">
<span class="icon">CLICK HERE</span>
</button>
<br>
<br>
</a>
<a href="example.com"class="locked">
<button class="locked-button">
<i class="fa fa-lock" aria-hidden="true"></i>
<span class="icon">CONTINUE</span>
</button>
</a>
I want that the last a element is locked, and if you click on the 2nd button, the class locked will be removed from the last a element and I will be able to click on the link.
It deletes the class but I still can't click the link. How to fix that?
Also, is there are smarter way to do that...
This event binding isn't removed from the <a> when its class="locked" is removed:
$('a.locked').click(function(e) {
e.preventDefault();
});
At least with direct bindings like this, jQuery only uses the selector initially to attach the event handler to all matching elements. It won't recheck the selector when the event is later triggered. Currently, you'll have to do that check yourself:
$('a').click(function (e) {
if ($(this).hasClass('locked')) {
e.preventDefault();
}
});
Though, if you have an overall parent element, you can use a delegated binding and jQuery will then recheck the (2nd) selector for you when the event is triggered.
<div id="parent">
<a href="example.com" target="_blank" id="action2">
<!-- ... -->
</a>
<a href="example.com" class="locked">
<!-- ... -->
</a>
</div>
$('#parent').on('click', 'a.locked', function (e) {
e.preventDefault();
});
So, just removing a css class will not work in your case.
You should remove the event handler to allow the button to be clicked, something like this should work:
$("a.locked").on("click.locked", function(e) {
e.preventDefault();
});
$(document).ready(function(){
$("button.button2").click(function(){
$("a.locked").off("click.locked");
$("a").removeClass("locked");
});
});
Working jsfiddle.
Like this?
Check out this SO question to read more about the toggle function I used.
$(document).on("click", "#ToggleLock", function(e) {
$('#Continue').prop('disabled', function(i, v) {
return !v;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id='ToggleLock'>Unlock/Lock</button>
<button onclick="location.href='http://www.example.com'" type="button" id='Continue' disabled>Continue</button>
Let me know if I have greatly misunderstood the question.
Remove the class is not enough, since you added a click event to all $('a.locked') you need use .off() to remove the click event after removing the class. Also try to target the specific element, you could add id="btn_continue" to 2nd button. ($("a") will target all <a> which is not what you want to do)
Note:
$('a.locked').click(function(e) {
e.preventDefault();
});
$(document).ready(function(){
$("button.button2").click(function(){
$("#btn_continue").off().removeClass("locked");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="example.com" target="_blank" id="action2">
<button class="button2">
<span class="icon">CLICK HERE</span>
</button>
<br>
<br>
</a>
<a href="example.com" id="btn_continue" class="locked">
<button class="locked-button">
<i class="fa fa-lock" aria-hidden="true"></i>
<span class="icon">CONTINUE</span>
</button>
</a>

Add javascript var to href

I have dropdown with different links, before that i have 2 radio buttons where you could select "mode".
<div class="radio">
<label><input type="radio" name="mode" checked="checked" value="mode1">MODE1</label>
</div>
<div class="radio">
<label><input type="radio" name="mode" value="mode2">MODE2</label>
</div>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a target="_blank" href="http://example.com/index.php?mode=">Site1</a></li>
<li><a target="_blank" href="http://example.com/index.php?mode=">Site2</a></li>
<li><a target="_blank" href="http://example.com/index.php?mode=">Site3</a></li>
</ul>
</div>
And i use this code snippet to detect what mode is selcted and add it to var mode:
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function () {
var mode=myRadio.filter(':checked').val();
});
});
What i want to do is to add javascript var $mode to href tags.
href="http://example.com/index.php?mode={$mode}
How could i accomplish this ?
I think only way would be to do this with some javascript function ?
Its not possible to just "print" var to href ?
JSFIDDLE: https://jsfiddle.net/DTcHh/18683/
Use data-* attribute to keep static href value to be used later. .change() will trigger change event initially to set the value of href attributes.
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function() {
var mode = myRadio.filter(':checked').val();
$('ul.dropdown-menu a').prop('href', function() {
return this.getAttribute('data-href') + mode;
})
}).change();
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="radio">
<label>
<input type="radio" name="mode" checked="checked" value="mode1">MODE1</label>
</div>
<div class="radio">
<label>
<input type="radio" name="mode" value="mode2">MODE2</label>
</div>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a target="_blank" href="http://site1.com/index.php?mode=" data-href="http://site1.com/index.php?mode=">Site1</a>
</li>
<li><a target="_blank" href="http://site2.com/index.php?mode=" data-href="http://site2.com/index.php?mode=">Site2</a>
</li>
<li><a target="_blank" href="http://site3.com/index.php?mode=" data-href="http://site3.com/index.php?mode=">Site3</a>
</li>
</ul>
</div>
Fiddle here
Check this fiddle I've modified for you: https://jsfiddle.net/so2fw1o4/1/
Add this to your myRadio.on('change', function
//here change the urls
$('.dropdown-menu a').each(function(){
$(this).attr('href', $(this).data('url') + mode)
})
And you will need to add data attribute to each link to store initial link
<a target="_blank" data-url="http://site. com/index.php?mode=" href="http://site. com/index.php?mode=">Site1</a>
Try this :-
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function () {
var mode=myRadio.filter(':checked').val();
$("ul.dropdown-menu li a").each(function(){
$(this).attr('href',$(this).attr('href').split('?')[0] + "?mode=" + mode);
});
}).change(); //trigger on page load
});
DEMO
Although you already have some answers here, I figured I would post another alternative (not necessarily any better).
You could add a class to each link, handle their click events, and set the new window's location yourself to achieve a similar effect.
The following is a code snippet modifying the jQuery in your fiddle:
$(document).ready(function() {
var myRadio = $('input[name=mode]');
var mode = myRadio.filter(':checked').val(); // Initial setting
myRadio.on('change', function () {
mode=myRadio.filter(':checked').val();
});
$('.mode-link').click(function(e) {
e.preventDefault(); //stop the click action
// Check if the mode has been set
if (mode) {
// Create the href value
var newHref = $(this).attr('href') + mode;
// Open the new tab/window with the correct href value
window.open(
newHref,
'_blank'
);
}
});
});
I simply added the mode-link class to each a element in the dropdown, stored the radio button value change in a new variable mode, added the click event handler, and finally handled the click event to create the new href value and open a new tab/window with that location.
If you didn't want the new tab/window you could simply set location.href = newHref but this wouldn't mimic the new tab/window opening, hence why I use window.open().
I have a modified sample here: JSFiddle

Getting data-* attribute for onclick event for an html element

<a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(?,?);">
Click to do something
</a>
I want to get the data-id and data-option values inside the function goDoSomething(10, 21) I have tried to use this reference: this.data['id'] but it did not work.
How can I do this?
You can achieve this $(identifier).data('id') using jquery,
<script type="text/javascript">
function goDoSomething(identifier){
alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
javascript : You can use getAttribute("attributename") if want to use javascript tag,
<script type="text/javascript">
function goDoSomething(d){
alert(d.getAttribute("data-id"));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
Or:
<script type="text/javascript">
function goDoSomething(data_id, data_option){
alert("data-id:"+data_id+", data-option:"+data_option);
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
Click to do something
</a>
Like this:
$(this).data('id');
$(this).data('option');
Working example: http://jsfiddle.net/zwHUc/
I simply use this jQuery trick:
$("a:focus").attr('data-id');
It gets the focused a element and gets the data-id attribute from it.
Check if the data attribute is present, then do the stuff...
$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
if(e.target.getAttribute('data-title')) {
var careerTitle = $(this).attr('data-title');
if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
}
});
function get_attribute(){ alert( $(this).attr("data-id") ); }
Read more at
https://www.developerscripts.com/how-get-value-of-data-attribute-in-jquery
here is an example
<a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>
$('.facultySelecter').click(function() {
var unhide = $(this).data("faculty");
});
this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get
you can directly use anchor id or data-action attributes to trigger the event.
Html Code
<a id="option1" data-action="option1" data-id="10" data-option="21" href="javascript:void(0);" title="Click Here">Click Here</a>
jQuery Code:
$('a#option1').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option')) ;
});
OR
$('[data-action="option1"]').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option'));
});
User $() to get jQuery object from your link and data() to get your values
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
Click to do something
</a>

Categories

Resources