Why doesn't this execute on first click? - javascript

In this jsFiddle
http://jsfiddle.net/littlesandra88/RBU8K/
have I the following code
function addRemove(id) {
alert("1");
$('#'+id).toggle(function() {
alert("2");
$('#'+id).after('<tr id="details" ><td>It worked</td></tr>');
}, function() {
alert("3");
$("#details").remove();
});
}
When clicking one time on "Details" it prints "1", but not "2" for some reason.
When the first click have been done, it works like it is supposed to.
But what's wrong, since the first click doesn't print out "2"?
And how can it be fixed?
Update
This is the solution
function addRemove(id) {
if ($('#accTable').find("[id*='details']").length == 0) {
$('#'+id).after('<tr id="details" ><td>It worked</td></tr>');
} else {
$("table tr").remove("#details");
}
}

You are only attaching a event handler (the toggle thingy) when calling addRemove(), then after you click again the event handler gets triggered.

Related

jQuery click if else only fires once and not when clicked

I am trying to create a mobile menu that has a burger menu, and when you click that menu, it should slide up and down. Before I implement this, I am testing how the jQuery code would work and I can only get it to console log when the page loads and not when you click the actual button.
jQuery:
function mobileMenu() {
$('.mobile-menu-button').click(function() {
$(this).data('clicked', true)
});
if ($('.mobile-menu-button').data('clicked')) {
console.log("Clicked!")
} else {
console.log("Not Clicked!")
}
};
mobileMenu();
For some reason it only console logs 'Not Clicked!' when you load up the page. But it isn't responsive when you actually click the button.
Into your function you add handler for a button. It set data-clicked to true only when you click on it.
Checking for data('clicked') executed immediately. If you set this param like into next code
<button class="mobile-menu-button" data-clicked="true">Click me</button>
you will receive into console "Clicked!".
In the next case
<button class="mobile-menu-button">Click me</button>
you will receive "Not Clicked!"
You are only performing the console.log once, when the mobileMenu() function is called. Simply updating the data inside the event handler will not cause the function to fire again, you need to explicitly put the function call inside your event handler, either by moving the event handler outside of the function, or having it call a different function, like so:
function logger() {
if ($('.mobile-menu-button').data('clicked')) {
console.log("Clicked!")
} else {
console.log("Not Clicked!")
}
}
function mobileMenu() {
$('.mobile-menu-button').click(function() {
$(this).data('clicked', true)
logger();
});
logger();
};
mobileMenu();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="mobile-menu-button">Button</button>

jQuery button click once do this, click twice restart

I would like a button to turn a text element to a certain string and then restart once it is off and make it blank again.
I tried this:
$('#checkbox5').on('toggle', function() {
$("#texty5").text("Video/film");
$('#checkbox5').on('toggle', function() {
$("#texty5").text("");
});
});
But it only works the one time you press and unpress it. Thanks!
You should probably only define one "toggle" event callback, and handle both scenarios.
$('#checkbox5').on('toggle', function() {
if ($("#texty5").text() === "") {
$("#texty5").text("Video/film");
} else {
$("#texty5").text("");
}
});

Choose only the first button

I'm trying to do that only one can happen, if you click yes or no. As it is now if you click "no" in the first time and "yes" in the second time, it will execute it twice .
function confirm() {
$("#no").one("click", function(){
return false;
});
}
$("#yes").one("click", function () {
//do something
});
thanks for help
Both events are attached at document.ready I assume, which means they will remain active indefinitely unless you specify otherwise.
The following approach is fairly basic, just set a variable 'hasClicked' to false. And as soon as either one of them is clicked, set 'hasClicked' to true. Each button has an if-structure that only executes the code IF 'hasClicked' is false.
Try the following:
var hasClicked = false;
function confirm(){
$("#no").one("click", function(){
if (!hasClicked){
hasClicked = true;
return false;
}
});
$("#yes").one("click", function () {
if (!hasClicked) {
hasClicked = true;
//do something
}
});
}
As you can't unbind an event binded with one() check this answer
So you'll have to work around like this:
function confirm() {
$("#no").bind("click", function(){
$(this).unbind(); // prevent other click events
$("#yes").unbind("click"); // prevent yes click event
// Do your stuff
});
}
$("#yes").bind("click", function () {
$(this).unbind();
$("#no").unbind("click");
// Do your stuff
});
Assign your buttons a class called confirmation. Set a event handler based on class. Read the value of the button to decide what you want to do.
$(".confirmation").one("click", function(){
if($(this).val() === 'yes'){
//do something
}else{
return false;
}
}

Intercept clicks, make some calls then resume what the click should have done before

Good day all, I have this task to do:
there are many, many many webpages, with any kind of element inside, should be inputs, buttons, links, checkboxes and so on, some time there should be a javascript that could handle the element behaviour, sometimes it is a simple ... link.
i have made a little javascript that intercepts all the clicks on clickable elements:
$( document ).ready(function() {
$('input[type=button], input[type=submit], input[type=checkbox], button, a').bind('click', function(evt, check) {
if (typeof check == 'undefined'){
evt.preventDefault();
console.log("id:"+ evt.target.id+", class:"+evt.target.class+", name:"+evt.target.name);
console.log (check);
$(evt.target).trigger('click', 'check');
}
});
});
the logic is: when something is cllicked, I intercept it, preventDefault it, make my track calls and then resme the click by trigger an event with an additional parameter that will not trigger the track call again.
but this is not working so good. submit clicks seams to work, but for example clicking on a checkbox will check it, but then it cannot be unchecked, links are simply ignored, I track them (in console.log() ) but then the page stay there, nothing happens.
maybe I have guessed it in the wrong way... maybe i should make my track calls and then bind a return true with something like (//...track call...//).done(return true); or something...
anyone has some suggestions?
If you really wanted to wait with the click event until you finished with your tracking call, you could probably do something like this. Here's an example for a link, but should be the same for other elements. The click event in this example fires after 2seconds, but in your case link.click() would be in the done() method of the ajax object.
google
var handled = {};
$("#myl").on('click', function(e) {
var link = $(this)[0];
if(!handled[link['id']]) {
handled[link['id']] = true;
e.preventDefault();
e.stopPropagation();
//simulate async ajax call
window.setTimeout(function() {link.click();}, 2000);
} else {
//reset
handled[link['id']] = false;
}
});
EDIT
So, for your example, this would look something like this
var handled = {};
$( document ).ready(function() {
$('input[type=button], input[type=submit], input[type=checkbox], button, a').bind('click', function(evt) {
if(!handled[evt.target.id]) {
handled[evt.target.id] = true;
evt.preventDefault();
evt.stopPropagation();
$.ajax({
url: 'your URL',
data: {"id" : evt.target.id, "class": evt.target.class, "name": evt.target.name},
done: function() {
evt.target.click();
}
});
} else {
handled[evt.target.id] = false;
}
});

Why alert popup a few times after a click event?

On a page there are couple of Add buttons (li .plus).
When you click on a Add button and assume json.success is false, it will then popup via $.colorbox plugin
The popup pull the data from href:"/Handle/Postcode/?val" + Val
There is a submit button (#submitButton) from the popup, when I click on the submit button, it keep popup alert box a few times, I dont understand why that happen? how to fix it?
$("li .plus").click(function(event) {
event.preventDefault();
var Val;
Val = $('#id').val()
$.getJSON(Address +"/Handle/Add", {
Val:Val
}, function(json) {
if (json.success == "false" && json.error == "NoArea") {
$.colorbox({
width:"450px",
transition:"none",
opacity:"0.4",
href:"/Handle/Postcode/?val" + Val
});
$("#submitButton").live('click', function() {
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
//Why does it popup a few times?
});
}
if (json.success == "true") {
Backet();
}
});
});
Thats an easy one, because you are using the .live() function to bind your click handler. If that code gets executed more than one time your binding happens more than one time.
You can either try to track the state of the binding and only apply it if it doesn't exist, or you can call your click function in the html with the onClick attr.
Edit: Just to clarify I meant something along the lines of -
HTML
<button id='submitButton' onclick="displayAreaCode();">Submit</button>
JS
function displayAreaCode(){
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
}

Categories

Resources