How to replace event handler when button is disabled - javascript

I have a situation where I have to replace all unauthorized controls in My UI from hidden state to disabled. Add a tooltip with un authorized text. Click the control to see unauthorized text.
I am able to update code but blocked at one point where I have to stop firing event on the control.
At the same time I have to show an alert on click of the event. How can I do this?
My trails are here in fiddle
Problem:
I have [clickdisabled = disable] click function which need to be called if control is disabled.
But at the same time on the control I have onclick="SearchDetails(); called which is throwing an error.
<input id="btnSearch" type="button" name="btnSearch" value="Search" onclick="SearchDetails();return false;" title="search" clickDisabled=disable />
//Add title to all disabled items in project
$('[clickdisabled=disable]').attr("title", "You are not authorized to perform this action.");
// Show unauthorized error on click of disabled control
$('[clickdisabled = disable]').click(function () {
alert($(this).attr("title"));
});

If you are expecting situations when the functions are not available, you could check if they exist before calling them:
<input id="btnSearch" type="button" name="btnSearch" value="Search"
onclick="if (typeof(SearchDetails) === typeof(Function)) SearchDetails();"
title="search" clickDisabled=disable />
Fiddle

What you need to do is keep track of both your normal onclick event handler and disabled onclick event handler. When you disable your button, remove the normal onclick event handler and add your disabled onclick event handler. When you re-enable the button, remove the disabled onclick event handler, and add the normal event handler back. You can do this with the jQuery .on() and .off() events (see the example below).
function onNormalClick(e){
alert('This is the default test button functionality.');
}
function onDisabledClick(e){
alert('This button is disabled.');
e.preventDefault();
e.stopPropagation();
}
function disableButtons(selector){
$(selector).css('color', '#888');
$(selector).off('click', onNormalClick);
$(selector).on('click', onDisabledClick);
}
function enableButtons(selector){
$(selector).css('color', '#000');
$(selector).off('click', onDisabledClick);
$(selector).on('click', onNormalClick);
}
$(document).ready(function(){
$('.test').on('click', onNormalClick);
$('#disabler').click(function(){
disableButtons('.test');
});
$('#enabler').click(function(){
enableButtons('.test');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='test'>Test</button>
<hr/>
<button id=disabler>Disable</button>
<button id=enabler>Enable</button>

You could prevent the default handling like this:
var button = $('#your_button_id');
button.click(function(e){
e.preventDefault();
alert("Your alert message for the user");
});

Related

jQuery cannot trigger button click from another button click

My goal is to replace a button with another button, but I am running into some issues. I am able to trigger the first button click and I am able to cause an alert with the second button click, but for some reason when I try to trigger the first button click in the click event handler of the second button, it doesn't work. What am I doing wrong? For some context, I'm doing this in Powerapps Portals by adding a Content Snippet.
$(window).load(function() {
//Code to Add Custom 'Register' Button (and Hide the original one- currently commented out)
$('#SubmitButton').after('<input type="submit" name="ctl00$ctl00$ContentContainer$MainContent$MainContent$mySubmitButton" value="Register" id="mySubmitButton" class="btn btn-primary">');
//$('#SubmitButton').hide(); *THIS WORKS*
//$("#SubmitButton").click(); *THIS ALSO WORKS*
$("#mySubmitButton").click(function()
{
//window.alert('yes!'); *THIS WORKS*
$("#SubmitButton").click(); // *THIS DOES NOT WORK*
});
});
You need to prevent the default action to stop the form from submitting when the button is clicked.
$("#mySubmitButton").click(function(e){
e.preventDefault();
$("#SubmitButton").click();
});
Alternatively, you can set the button's type to "button" so clicking it does not submit the form by default.
$('#SubmitButton').after('<input type="button" name="ctl00$ctl00$ContentContainer$MainContent$MainContent$mySubmitButton" value="Register" id="mySubmitButton" class="btn btn-primary">');

Overlapping events from different elements double fire the same function in JQuery

I have a dead simple search form:
<div>
<input id="searchArea" type="text" value="" placeholder="Enter your search terms">
<button id="searchButton">Search</button>
</div>
and a snippet of Javascript controlling it:
function searchFunction() {
console.log("This is a POST request being send to the server");
}
$("#searchButton").on("click", function(e) {
e.preventDefault();
searchFunction();
})
$("#searchArea").on("change", function(e) {
e.preventDefault();
searchFunction();
});
The problem is that click and change overlap in functionality and so I get the following:
When I type something in the text box and then click elsewhere in the screen, searchFunction is fired properly but if "elsewhere" becomes the search button, then searchFunction double fires.
My question is this: Once inside the click handler, is there any way to cancel the change handler from firing as well which would otherwise cause searchFunction to double fire?
Mind that searchArea and searchButton don't have a parent-child relationship which means conventional methods like preventDefault and stopPropagation won't work.
You can see it in action in this fiddle.

Lost "click" event during AJAX refresh

$(":input").on("change", function(e) {
console.log("change triggered");
$("#section").html("<button id='order'>Order</button>");
registerButtons();
});
function registerButtons() {
$("#order").on("click", function(e) {
console.log("click triggered");
alert("Hello World");
});
$("#order").on("mousedown mouseup", function(e) {
console.log(e.type + " triggered");
});
}
registerButtons();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="123"/>
<div id="section">
<button id="order">Order</button>
</div>
I have a web page with a button and some input fields.
On the button an click event is registered
On the input fields an change event is registered
The onChange will trigger an AJAX server call, and the result will replace parts of the web page - including the button. After AJAX result is processed, all listener are registered again.
Now the problem. A user changes the value of an input field, and clicks directly the button - but to slow (lets assume the user needs 500ms for the click), so the onChange event is fired and the page is "updated/replaced". Now the "old" button fires an onMouseDown and the "new" button fires an onMouseUp event - but no onClick.
My current workaround is, to register the two mouseDown/mouseUp events, get the timestamp of the mouse down, and if the mouse up comes in 2 seconds, do what should be done by the onClick.
It is no option to remove the button part from the AJAX response - in worst case the button could be removed and replaced by an user info.
My hope is, that there is a better solution... any ideas?
You can take advantage of the event delegation and set your listener on the container instead of the button.
You are adding a click listener to your old button and your adding a new button to the dom. So the click won't work.
The button wasn't working because for some reason it can't focus when you hover over it. So I added a getFocus method and now it should work.
$("input").on("change", function(e) {
console.log("change triggered");
$("#section").html("<button id='order'>Order</button>");
});
function registerButtons() {
$('#section').on("mouseup", '#order', function(e) {
alert('Clicked!');
});
}
registerButtons();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="123"/>
<div id="section">
<button id="order">Order</button>
</div>
I just found out that jQuery provides a sweet API that can be used for event delegation. This way we don't have to manually check for event target. Check it out http://api.jquery.com/on/
$("input").on("change", function(e) {
console.log("change triggered");
$("#section").html("<button id='order'>Order</button>");
});
function registerButtons() {
$("#section").on("click", '#order', function(e) {
console.log("click triggered");
alert("Hello World");
});
$("#section").on('mouseover','#order', function(e){
$(this).focus();
});
}
registerButtons();

Why jquery click event is not firing on firefox?

I have this function in JS :
jQuery(function ($) {
$(document).on("click", ".botaoExcluirRecibos", function (e) {
e.preventDefault();
alert("Fired!");
});
});
And in my asp.net page i have this button:
<div class="listaExcluir" id="listaExcluir">
<ul id="listaArquivos">
<li>
<div class="voceAnexou"></div>
<div class="divInformacoesAtendimento divInformacoesAtendimentoTabelaRecibo">
<p>VocĂȘ anexou:<strong> file1.png </strong></p>
<button class="botaoVermelhoPequeno botaoExcluirRecibos" onclick="return false;">Excluir</button>
</div>
</li>
</ul>
</div>
The button is added dynamically on the li tag, and more buttons can be added by the user.
It's not firing the click event at FIREFOX , but at CHROME is.
Obs: I had to add the onclick event inline on the button for preventing the postback issue.
First, you can add "return false;" to your event handler and it will avoid postbacks - you don't need to have it inline.
Second, I would recommend a binding function:
function BindClick(){
$(".botaoExcluirRecibos").unbind("click"); // To prevent double-binding click events!
$(".botaoExcluirRecibos").on("click", function(e){
e.preventDefault();
console.log("Fired!"); //Use the console instead of alerts for debugging purposes!
return false;
});
}
Now, just call:
BindClick();
Every time you add a control to the page that will need this event handler. This should work in every browser.

Disabled button still fires using ".click()"

It seems disabled button "onclick" function is still fired when triggering it programmaticaly, eg:
<div>
<input type="button" onclick="save()" id="saveButton" value="save" disabled="disabled" />
<input type="button" onclick="byPassDisabled()" value="bypass disabled button"/>
<div id="counter">0</div>
function save(){
var count = parseInt($('#counter').html());
$('#counter').html(++count);
}
function byPassDisabled(){
$('#saveButton').click();
}
see http://jsfiddle.net/WzEvs/363/
In my situation, keyboards shortcuts are bound to functions triggering the ".click()" on buttons. I'll find it very annoying to have to disable the shorcuts or check if the button is disabled myself. I'd prefer a general solution fixing this problem.
But why? This behavior doesn't seem fair to me.
Any workaround?
The attribute only disables user interaction, the button is still usable programmatically.
So yeah, you gotta check
function byPassDisabled(){
$('#saveButton:enabled').click();
}
Alternatively don't use inline handlers.
$(document).on('click', '#saveButton:enabled', function(){
// ...
});
For future use...the OP code works because jQuery will still call it's own handlers even if the DOM element is disabled. If one were to use vanilla javascript, the disabled attribute would be honored.
const element = document.getElementById('saveButton');
element.click() //this would not work
You can programmatically trigger click on a disabled button.
There are ways to find if the event is a click on button by user or it has been trigger programmatically. http://jsfiddle.net/WzEvs/373/
$(function () {
$("#saveButton").on('click', function (e) {
if (!e.isTrigger) {
var count = parseInt($('#counter').html());
$('#counter').html(++count);
}
});
$("#bypassButton").on('click', function (e) {
$("#saveButton").click();
});
});
e.isTrigger is true if you call the click() programmatically. Basically you are triggering the click event manually in code.
You can trigger click still although made it disable .As Spokey said it just shows the user-interaction(the usability still persists that can be turned on programmatically) .
off or unbind the click will solve this issue.
Thanks

Categories