if statement around onclick - javascript

What is the best way to ignore running code when a button is clicked? I am trying the following but I currently get not reaction how I want it done.
if (!document.getElementById('btn_Cancel').getAttribute('onclick')) {
// code not to be ran when button is clicked
By default code gets ran when a textbox goes onblur so do not want that code ran when button gets clicked
}

You're going to want to make a reference to that element, so you don't end up looking it up each time it's clicked and you'll need a variable to keep track of whether it's been clicked or not:
var cancelButton = document.getElementById('btn_Cancel'),
clicked = false;
cancelButton.addEventListener('click', function() { clicked = !clicked; }, false);
// assuming this is in a loop or something:
if(!clicked) {
// running code
}
else {
// clicked, do nothing
}

Related

alert() function is looping when called in focus() event

I Want an Alert pop-up when focusing on input. It pops up correctly but when I click on 'OK' or 'x' i.e cancel, it Loops infinitely and never closes.
$('input').focus(function () {
alert('hello');
});
This is because the input is assuming the focus again when the alert is closed (which is the new focus when it appears - notice the outline around the button in the dialogue?)
If you only want to make the alert show once, you could perhaps write something a resembling this:
let hasShownAlert = false
$('input').focus(function () {
if (!hasShownAlert) {
hasShownAlert = true
alert('hello')
}
})
Of course you could improve this with state containers or something, but this is the simplest way you could achieve it. (Note: the hasShownAlert variable has to be defined outside of the onfocus handler, otherwise it'll be cleared up by the garbage collector.)
Updated: So if you don't want it to only show once, there are a couple of things you could do. The first, the simpler, would be listening for the click event, rather than focus. The second way could be setting a didShowAlert variable -- inverting the value each time the handler is fired. E.g...
let didShowAlert = false
$('input').on('focus', (ev) => {
if (didShowAlert) {
didShowAlert = false
} else {
didShowAlert = true
alert('hello')
}
})
You could try a hack like
$(document).on("focus", 'input:not(.unFocus)', function() {
alert('hello');
$('input').addClass('unFocus');
setTimeout(function() {
$('input').removeClass('unFocus');
}, 10);
});
It may not be the ideal way to do it, but it works :)

$ionicPlatform onHardwareBackButton runs multiple times

I have an issue with the back button running more than once.
currently I'm in my "messages" $state, and if I press the back button the following code works as normal.
var messageIsClosed = true;
$ionicPlatform.onHardwareBackButton(function(event){
event.stopPropagation();
handleBackButton();
})
var handleBackButton = function(){
if(messageIsClosed){
$state.go("dash");
} else {
messageIsClosed = false;
}
}
however, if I go to another $state (say, "dash") and then return to "messages", pressing the back button will make the above code run twice. Then if I go back to "messages" again it runs 3 times, then 4. For each time I visit the "messages" view/controller the back button code will run an extra time
I have no idea why
The onHardwareBackButton will run multiple times and this is normal in your case. This is because you are registering the event every time you visit the messages state.
To avoid the multiple registration of the event you could useoffHardwareBackButton() and de-register the event when moving away from the current state.
Example code:
This is the callback
var hardwareBackButtonHandler = function() {
// add you back button logic here
console.log('Hardware back button pressed');
}
Register the back button event like that:
$ionicPlatform.onHardwareBackButton(hardwareBackButtonHandler);
Then when moving away from the current state you can un-register like that:
$ionicPlatform.offHardwareBackButton(hardwareBackButtonHandler);

Set variable on back button click

I have a function I dont want to run if the broswer back button was clicked. I am attempting to use something like the below:
var backButtonClicked = false;
window.onpopstate = function() {
alert("Back clicked");
backButtonClicked = true;
};
then later I am trying to use the variable like:
if(!backButtonClicked) {
//run function if not back button clicked
}
However with the code above the alert is not getting fired when I hit the back button.
window.onpopstate = function() {
alert("back clicked");
backButtonClicked = true;
};
history.pushState({}, '');
With the code above the alert gets fired when I click the back button, however the browser doesnt navigate back to the previous page unless I click the back button for the second time. Is there something I am doing incorrect here or is there a better approach to achieve what I am trying to do?
My coding skills are not very good when I have very little time to type. But maybe an eventlistener would be another approach to the problem you can maybe consider?
For examples and reference from an excellent source:
http://www.w3schools.com/js/js_htmldom_eventlistener.asp
Hope this helps, and good luck!

jQuery prevent checkbox checking nested inside another DIV

I've looked at and tried numerous answers on this topic but can't seem to find a solution that works. I might be missing something obvious in which case I apologise but here's my problem:
I have a checkbox nested within a DIV element, this DIV element has a jQuery click event attached to it which then checks whether the checkbox is checked or not and then either checks/unchecks it. Depending on whether it has been checked/unchecked it then sends a variable to a PHP script to add into a session variable.
This all works fine when it's the DIV that has been clicked but when the checkbox is clicked I think some bubbling occurs as it fires the event for unchecking the checkbox every time. I've tried using stopPropogation(); and preventDefault(); attached to the checkbox click event but to no avail.
Here's some sample code to try and make this clearer:
Checkbox HTML code:
<div class='bundle_offer' id='bundle_offer_0'>
<input type="checkbox" />
</div>
Click function:
// Click function on bundle offer div to add booster
$(".bundle_offer").click(function (event) {
// IF its not the checkbox clicked, send over the div id
if (event.target.type !== 'checkbox') {
var bundle_offer_div_id = "#"+this.id;
bundle_offer_click(bundle_offer_div_id);
}
// ELSE find div id and send it
else{
var bundle_offer_div_id = $(this).closest(".bundle_offer").attr("id");
bundle_offer_div_id = "#"+bundle_offer_div_id;
bundle_offer_click(bundle_offer_div_id);
}
}); // end bundle offer click function
the bundle_offer_click function simply takes the id of the DIV clicked, finds the checkbox, checks/unchecks it and then sends the appropriate variable to the PHP script via AJAX.
EDIT:
I managed to fix the problem by moving round the logic a bit, here is what I changed it to:
// Click function on bundle offer div to add booster
$(".bundle_offer").mouseup(function (event) {
// Get whether checked or not
var isChecked = $(this).find('input').is(':checked');
// IF its not the checkbox clicked
// check/uncheck
// send over the div id
if (event.target.type !== 'checkbox') {
if(isChecked == false){
// Check
$(this).find('input').attr('checked',true);
}
else{
// Uncheck
$(this).find('input').attr('checked',false);
}
var bundle_offer_div_id = "#"+this.id;
bundle_offer_click(bundle_offer_div_id, isChecked);
}
// ELSE find div id and send it
else{
var bundle_offer_div_id = $(this).closest(".bundle_offer").attr("id");
bundle_offer_div_id = "#"+bundle_offer_div_id;
bundle_offer_click(bundle_offer_div_id, isChecked);
}
}); // end bundle offer click function
Main difference is using the mouseup function instead and doing the logic for checking/unchecking the checkbox within that mouseup function rather than the bundle_offer_click one.
In case you click on check box browser automatically check/uncheck checkbox. you don't need do that using JavaScript.
I believe inside bundle_offer_click you are checking/unchecking checkbox. you should pass a flag as second parameter in bundle_offer_click flag value should be depend on clicked element. and inside bundle_offer_click based on flag take action on checkbox.
code:
function bundle_offer_click(id, isCheckBoxClicked){
if(isCheckBoxClicked){
//do nothing on check box
}
}

Detecting form changes using jQuery when the form changes themselves were triggered by JS

I have a list of radio buttons that I can toggle "yes" or "no" to using Javascript.
$(document).ready(function(){
$('#select-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', true);
$('input[type="radio"]', this).eq(1).attr('checked', false);
});
});
$('#deselect-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', false);
$('input[type="radio"]', this).eq(1).attr('checked', true);
});
});
});
this works just fine. Now I have a separate piece of code that detects when a user has changed something, and asks them if they want to leave the page.
var stay_on_page;
window.onbeforeunload = confirm_exit;
$('.container form input[TYPE="SUBMIT"]').click(function(){
stay_on_page = false;
});
$('#wrapper #content .container.edit-user form').change(function(){
stay_on_page = true;
});
function confirm_exit()
{
if(stay_on_page){ return "Are you sure you want to navigate away without saving changes?"; }
}
The problem is that if the user uses the first piece of functionality to toggle all radio buttons one way or another. The JS detecting form changes doesn't see that the form was changed. I have tried using .live, but to no avail. Anyone have any ideas?
I do something similar to this by adding change() (or whatever's appropriate, click() in your case I suppose) event handlers which set either a visible or hidden field value, then check that value as part of your onbeforeunload function.
So, my on before unload looks like:
window.onbeforeunload = function () {
if ($('#dirtymark').length) {
return "You have unsaved changes.";
}
};
And, or course, dirtymark is added to the page (a red asterisk near the Save button), when the page becomes dirty.

Categories