Jquery Click to hide/show div not working - javascript

Need to use one single button to toggle the show and hide for div
my code looks something like this
function showTable(number){
$('#div_'+number).show('slow');
$('#button_'+number).html("Hide Table").click(function(){
hideTable(number);
return false;
});
}
function hideTable(number){
$('#div_'+number).hide('slow');
$('#button_'+number).html("Show Table").click(function(){
showTable(number);
return false;
});
}
<div id="div_1" style="display:none"></div>
<button id="button_1" onClick="javascript:showTable(1)">Show Table</button>
<div id="div_2" style="display:none"></div>
<button id="button_2" onClick="javascript:showTable(2)">Show Table</button>
<div id="div_1" style="display:none"></div>
<button id="button_3" onClick="javascript:showTable(3)">Show Table</button>
The function is working fine at first. But after i show and hide it once, whenever I tried to show it again, it starts chaining show/hide/show/hide by itself without any clicks. And the more I do it, the longer it does the chaining. It seems it's just a loop that everytime it doubles the amount of looping(like show/hide for 2/4/8/16/32 times ....) the more I do the longer it loops. Anyone have a clue what's going on?
I tried to remove the click part in the hideTable function, the loop stops but still whenever I try to hit showTable, it will show then hide it self automatically like it's auto executing the stuff in the click function without any clicks...
Also is there anyway to use the jquery tagging style to call the function instead of using onclick? i know I can do like
$("#button_1").click(function(){......................});
$("#button_2").click(function(){......................});
$("#button_3").click(function(){......................});
but is there anyway I can group all of them together into a single function and still able to tell which button is clicked? Because I need a way to track which div to show and hide, and change the the text in corresponding button. Thank you very much in advance. m(_ _)m

You're piling on more and more redundant event handlers with each "click". That's what those calls to ".click()" in the handlers do — add another event handler.
You only need to add an event handler once. And adding an event handler does not remove the prior handler. Since you're using jQuery, use it to add the handlers, not old-fashioned "onclick" attributes.
Give all those <div> elements a class value, like "toggled".
<div id="div_1" style="display:none" class='toggled'>
You can do the same with the buttons. Then you can set up event handlers by using the class to refer to them in a jQuery selector.

A better way to do this is with toggle. Refer to JQuery toggle showhide

you should gove all your divs the same class eg class="toggleable" on the ones you want to toggle.
Then try:
jQuery(".toggleable input[type='button']").click(function()
{
jQuery(this).closest("div.toggleable").toggle();
});
This will put an onlick on your buttons inside your div which will find the closest parent div with class toggleable and will either hide/show your div.
To read about toggle():
http://api.jquery.com/toggle/
to read about selectors:
http://api.jquery.com/category/selectors/

I agree with Pointy but since I can't seem to add onto the answer, I must make another.
$('[data-show-table]').click(function() {
var $this_button = $(this);
$('#div_' + $(this).attr('data-show-table')).toggle(function() {
var msg = $(this).css('display') == 'none' ? 'Show table' : 'Hide table';
$this_button.html(msg);
});
});
<div id="div_1" style="display:none">Table 1</div>
<button id="button_1" data-show-table="1">Show Table</button>
<div id="div_2" style="display:none">Table 2</div>
<button id="button_2" data-show-table="2">Show Table</button>
<div id="div_3" style="display:none">Table 3</div>
<button id="button_3" data-show-table="3">Show Table</button>

Related

Remove DIV using button

Let's say I have a div with a button inside:
<div>
<button id='delete_btn'>delete</button>
</div>
What would be the jQuery code to delete that div and ONLY that div
As I have another button that dynamically adds copies of that sample code above.
So I could have something like this, but I only want the div that contains the button pressed, to be deleted.
<div>
<button id='delete_btn'>delete</button>
</div>
<div>
<button id='delete_btn'>delete</button>
</div>
thanks!
id should not be duplicate in a document. Use class instead. Inside the click handler function, you can target the parent of this element to remove:
$(document).on('click', '.delete_btn', function(){
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class='delete_btn'>delete</button>
</div>
<div>
<button class='delete_btn'>delete</button>
</div>
This can easily be performed with Vanilla JS and the newer remove() method. If IE-support is not a necessity, consider the following; or, if IE-support is needed, it wouldn't take much to amend the following:
document.addEventListener('click', function (e) {
if (e.target.matches('.delete_btn'))
e.target.parentNode.remove()
}, false);
<div>
<button class='delete_btn'>delete 1</button>
</div>
<div>
<button class='delete_btn'>delete 2</button>
</div>
event / state
This binds an event to the document (ancestor of the button). The benefit from this is that the click handler will be called for any new delete buttons that are dynamically created after the page has loaded (and will still function).
class vs id
This also uses class in place of id. This is because id should be reserved for unique values and class is intended to be a handle to like-elements. JavaScript can produce unexpected behavior if multiple elements are named with the same ID.
remove()
Using remove() an element can be removed from the DOM as expected. An older method would be to call the removeChild() on the parent (e.g., parent=e.target.parentNode; parent.parentNode.removeChild(parent))
more ES6
Of course, you could simplify the code using a named-argument/destructuring-assignment, which essentially assigns event.target to a variables named btn and The code can further be reduced, using a common arrow function. See below.
document.addEventListener('click', ({target: btn})=>{
btn.matches('.delete_btn') && btn.parentNode.remove()
}, false);
<div><button class='delete_btn'>delete 1</button></div>
<div><button class='delete_btn'>delete 2</button></div>
{target: btn} plucks the event argument being passed into the function and takes the value of the target property and assigns it to a new variable called btn. If you just had {target} (without the assignment), in the function body you would replace btn with target (e.g., target.matches(…), target.parentNode)

set event function trigger in looping with jquery

I would like to ask something about set event trigger with jquery.
First of all, i have a form with many buttons ( btnadd1 , btnadd2, btnadd3 , ... )
I have this code:
for(i=1;i=<3;i++){
$('.btnAdd'+i).click(function(){
alert(i);
});
}
The code should be alert(1) when i click btnadd1 , alert(2) when i click btnadd2,
but the problem is when i click btnadd1, btnadd2, or btnadd3 it alerts "3"
My assumption is that the function overwrites the previous function. Does anyone have a solution for this problem?
This is a common closure issue. You can work around it like this:
$('.btnAdd'+i).click(function(idx){
return function(){alert(idx);};
}(i));
JSFIDDLE
The issue deals with closure inside loop.
Better you could use a user defined attribute in your button and use a single classs for binding the event. see #bipen's answer.
<button class= "someclass" data-value="1"> click</button>
<button class= "someclass" data-value="2">click </button>
$('.someclass').click(function(){
alert($(this).attr('data-value'));
});
Check Fiddle
http://jsfiddle.net/hoja/3jt5furd/5/
Avoid using closure inside a loop...better is to assign a single class to all the buttons and register single event for that..make use of data attributes.
$('.someclass').click(function() {
alert($(this).data('value')); //using jquery's data function
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="someclass" data-value="1">
button1
</button>
<button class="someclass" data-value="2">
button2
</button>
there are other solution to achieve what you want, using attribute selector [class^="btnadd"] and so on but i think this solution is better and readable.

Clicking on image does nothing

I am trying to create a click event for an image using jQuery but I fail every time I try.
First I have a div:
<div id="price-holder"></div>
then I am using jQuery to insert this HTML by using the following:
$("#price-menu li:nth-child(2)").click(function() {
var pregHTML = $("#cakesmash-price").html();
$("#price-holder").html(pregHTML);
});
However, using this HTML doesn't work
<div id="cakesmash-price" style="display:none">
<img id="cake" src="images/order.png" height="32px" onclick="pregbasic(this);">
</div>
I tried to use the attribute onclick for the image and also tried using jQuery's selector with the ID like so
$("#cake").click(function(){
})
but both didn't work.
Can anyone help me?
Thanks
This assumes that the element is actually being added to the page.
I am betting you are adding the click event before you add the element to the page meaning the selector did not find anything so it did not add the event.
Either add the event after you add the element or use event delegation.
$("#price-holder").html(pregHTML);
$("#cake").click(function(){
});
or
$("#price-holder").on("click", "#cake", function () {
});
Your error could be due to your choice of selectors "#price-menu li:nth-child(2)". Try using the JS .children and .eq selectors. Also if your code was added dynamically consider using the .on() event handler rather than the .click().
Just start with the DOM you actually want, without using jQuery to do this:
<div id="price-holder">
<div id="cakesmash-price" style="display:none">
<img id="cake" src="images/order.png" height="32px">
</div>
</div>
Then you can just add you click handler on #cake:
$('#cake').on('click', function (event) {
// your logic goes here
});

Toggle css of 1 of multiple classes of the same name

I have dynamically created divs..
<div class="container"></div>
Each div has an input element within it..
<div class="container">
<input type="button" class="container_button" value="toggle" />
</div>
My goal is to minimize only the container div of the button clicked..
$('.container_button').onclick(function() {
$('.container').css('height','20px');
});
How can I achieve this when multiple divs of the same class exist?
jQuery object doesn't have onclick method, you can use on method instead, as you are generating the element dynamically you should also delegate the event.
$(document).on('click', '.container_button', function() {
$(this).parent('.container').css('height','20px');
// ^--- clicked element
});
You need to find .container relative to the DOM element that was clicked.
$('.container_button').click(function () {
$(this).closest('.container').css('height', '20px');
});

Linked event listeners using jQuery

I have this HTML structure
<div class="buttons">
<button data-icon="ui-icon-disk" class="save">Save1</button>
<button data-icon="ui-icon-check" class="ok">OK1</button>
<button data-icon="ui-icon-trash" class="delete">Delete1</button>
<button data-icon="ui-icon-close" class="close">Close1</button>
</div>
There are many blocks in the page like this one.
Some buttons come with click handlers functions (save and delete buttons).
What I want to do is: if someone click on an ok button, the corresponding save button click bound function should run.
My code:
$('.save').click(function(){
alert('save');
});
$('.ok').click(function(){
$('.save').click();
});
This is wrong, when I click on a ok button all save buttons fires... not only the one within the same buttons group.
Demo illustrating my problem.
Use $(this).siblings('.save').click() to select only siblings of the clicked button instead of all matching buttons in the whole document.
Demo: http://jsfiddle.net/ThiefMaster/nMnm7/2/
Docs: http://api.jquery.com/siblings/
use siblings
$('.ok').click(function(){
$(this).siblings('.save').click();
});
DEMO
http://api.jquery.com/siblings/
$('.ok').click(function(){
$(this).siblings(".save").click();
});

Categories