How to append the div element in jquery if don't exist - javascript

I am adding the form my current list in a div box at the bottom of the table.
I am appending the div box when someone clicks on add button.
But when i click add button multiple times , then many div boxes are appended.
Is there any way that no matter how many times I click the button, only one instance gets append to div box.
This is my code
$var = $(this).parent().parent();
$var.append($('.jq_div')[0].outerHTML);

attach your listener using .one().
$("button").one('click', function(){
// Your code
});
Read more: http://api.jquery.com/one
This is under the assumption that you're using jQuery 1.7+

One simple solution would be having a boolean flag that you can toggle once your button is clicked. Additionally, there is actually a jQuery function that provides this exact functionality.
It's called one() -
Attach a handler to an event for the elements. The handler is executed
at most once per element.
So your code would look something like this -
$("#someTrigger").one('click', function(){
$var = $(this).parent().parent();
$var.append($('.jq_div')[0].outerHTML);
});
The boolean method is also very simple -
var wasClicked = false;
$("#someTrigger").on('click', function(){
if (wasClicked == false){
// append your form
wasClicked = true;
}
});
Reference -
one()

Related

jQuery Toggling next row in dynamically created table with dynamically created button

I have a jQuery dynamically created table that appends data from json file.
one of the rows of the table is a row of buttons that are appended into a row variable that is appended into the table:
var like = $("<a href='index.html'><button class='likeBtn'>like</button></a>");
var comment = $("<a href='index.html'><button class='comBtn'>comment</button></a>");
var toggle = $("<a href='index.html'><button class='togBtn'>show/hide comments</button></a>");
row3.append(like).buttonset();
row3.append(comment).buttonset();
row3.append(toggle).buttonset();
$("#table").append(row3);
now I need to toggle the row below in the table when clicking the toggle button.
this is my onclick function:
$(function(){
alert("in");
$('.togBtn').click(function() {
alert("in2");
$(this).closest('tr').toggle();
});
});
when I put alerts inside the click function I don't see them, I do see alerts from the function that holds the click function. for example- I see "in" but I don't see "in2".
and of course the row is not toggled.
commentRow is the class of the row that needs to be toggled.
I tried lots of options like-
$("#table").closest('.commentRow').toggle();
also with next() , All(), and many others and I can't get it to work!!!
please - your thoughts on this.
All help will be much appreciated!
It's due to the dynamically generated content, try that:
$(document).on('click','.togBtn',function(e) {
alert("in2");
$(this).closest('tr').toggle();
// or return false; // it does both preventDefault & stopPropagation.
});
This is called event delegation. This technique is only used when you have generated dynamic DOM nodes like as you are doing in your code.
So, in this case all the events were bound when page was initially loaded and the elements are generated after page load, due to that browser didn't registered any event for those elements because of unavailablity. In this case event has to be delegated to the static parent node or to the document itself because it is always available.
Syntax for event delegation using .on() method:
$(staticParent).on(event, selector, cb);
With the help of the answers posted here I found a solution that works:
$(document).on('click','.togBtn',function(e) {
alert("in2");
e.preventDefault();
$(this).parents("tr").next().slideToggle();
// or return false; // it does both preventDefault & stopPropagation.
});
Thanks all for your help!

Toggling if a condition is met on table elements

I have a table. Each column has a button at the top. If the td elements below within the column have content in them, then hide the button. If not then display the button and onClick add class active too the td element.
$(document).ready(function (){
$('.button-fill').on("click", function() {
var i=$(this).parent().index();
if($(this).closest("tr").siblings().find("td:eq("+i+")").text()=="")
$(this).hide();
else
$(this).show();
});
<!-- Fill in the td -->
$('.button-fill').on("click", function() {
var i=$(this).parent().index();
$(this).closest("tr").siblings().find("td:eq("+i+")").addClass("active");
//});
});
});
http://jsfiddle.net/ujw0u6au/
I've created a jsfiddle. I don't know what i'm doing wrong? Thank you
Since you have bind the button toggle logic inside button click - you will always have the button in the starting. When you will click on the button only then it will first hide the button and then make the content active.
In case you want this behavior in the starting as soon as the page loads, you should change below line (the 2nd line in your code) from your code -
$('.button-fill').on("click", function() {
to
$('.button-fill').each( function(i,e) {
also, you should not use <!-- Fill in the td --> style of commenting in JavaScript.
I can see you are having two "click" event handler on same class. Instead of it, you can merge it as well.
Here is the optimized version of your code :
JavaScript :
$(document).ready(function (){
$('.button-fill').on("click", function() { //Only one click event handler
var $this = $(this);
var i=$this.parent().index();
var $trSibling = $this.closest("tr").siblings();
$this.toggle($trSibling.find("td:eq("+i+")").addClass("active").text() != ""); //adds the class as well and check the text as well.
})
$(".button-fill").trigger("click");
// explicitly clicking on button to make sure that initially button should not be shown if column text is not empty
});
JSFiddle link : http://jsfiddle.net/ujw0u6au/1/
Is this the same what you want?
#Vijay has the right answer, but as a side note, you need to change this:
if($(this).closest("tr").siblings().find("td:eq("+i+")").text()=="")
to this
if($(this).closest("tr").siblings().find("td:eq("+i+")").text()!="")
if you want to hide the button when there is content, instead of the other way around (notice the != near the end).

How do I get an event listener to work on an element that is added to my html via javascript?

I'm adding some HTML to my document via javascript. I also add a button to my HTML via this javascript function. I want this button to have an event listener, but this doesn't seem to work on the element added with javascript. Is it possible to fix this?
my js:
$('#content-overview li').on('click',function(){
// Clear previous videos
$('.content-overview-row').remove();
// Insert new video
var vimeoId = $(this).data('vimeo');
var html = '<li class="content-overview-row"><div class="content-overview-video"><iframe src="http://player.vimeo.com/video/'+vimeoId+'" width="950" height="534"></iframe><a id="close-video"></a></div></li>';
// Find end of row and insert detailed view
var nextRow = $(this).nextAll('.first-in-row:first');
if(nextRow.is('li')){
nextRow.before(html);
}
else{
//last row
if($(this).hasClass('first-in-row'))
{
//first item clicked in last row
$(this).before(html);
}
else{
$(this).prevAll('.first-in-row:first').before(html);
}
}
return false;
$('#close-video').click(function() {
console.log("works");
});
});
close-video is the close button I am talking about.
You need to bind the click event to an element which exists in the DOM when the page is loaded, and delegate the dynamically added element, like so:
$(document).on('click', '#close-video', function() {
...
});
You should change document for the element closest to your #close-video so that it doesn't have to bubble right up to the document.
Also, you're returning false; before the #close-video click handler, so that code would never be executed anyway. Move it outside of your #content-overview li click handler.

Adding jQuery event handlers to elements with wildcard IDs

I currently have the following in a document.ready block:
$("[id^=summaryDetailLink_]").each(function(index) {
var splitID = this.id.split("_");
this.click(alert('clicked: '+splitID[1])); //toggleDetail(splitID[1])
});
Ultimately I want to detect when a TD with an ID of "summaryDetail_" is clicked on and fire the toggleDetail function with the ID taken from the TD.ID attribute.
The above seems to generate the correct ID (the alert popsup) but is firing when the page loads rather than when I click on the element.
So problem number 1 - why is it firing on page load rather than creating a handler for click on each element and waiting for that click?
Problem number 2, in reading around this issue it seems it would be more sensible to create a single event handler on the table rather the TD then determine which TD element was clicked. How would I convert the code to do that?
Answer to first question:
$(function() {
$("[id^=summaryDetailLink_]").click(function() {
var splitID = $(this).id.split("_");
alert('clicked: '+splitID[1])
});
}
Answer to second question, you can do this:
$('table#yourtable').on('click', '[id^=summaryDetailLink_]', function(e) {
var splitID = $(this).id.split("_");
alert('clicked: '+splitID[1])
});
I think you're misunderstanding how the click handler works:
$(function() {
$("[id^=summaryDetailLink_]").click(function() {
var splitID = $(this).id.split("_");
alert('clicked: '+splitID[1])
});
}

Trigger event on specific condition

I have a div that will serve as container to other element, I have buttons that add element to that div.
Please see the demo for a get an idea about it.
So, what I want to do is to check before adding a new element is the div reached a maximum number of elements that I define, let's say 4.
I can check this condition before every add, but I am sure this is not the best way (we learned that if the code contains copy/paste then is not the best solution) Also, this is just a sample, in my case, I have many buttons..
Is there a way to have a listener like this?
$('#container').bind('divFull', function(){
//My code
});
So that I can disable buttons..
First, you have to listen to DOM change event, then you can trigger a custom event based on the number of children
$('#container').bind('DOMSubtreeModified', function(){
if($(this).children().length>=4){
$(this).trigger('divFull');
}
});
then you can bind to your custom divFull event
$('#container').bind('divFull', function(){
alert('container is full');
$('button').prop('disabled',true);
});
a working demo based on your example
I change a bit the #skafandri method because the event DOMSubtreeModified doesn't work on IE < 9 and it's depreciated.
The main change is to create a function which will call the divFull event if their is 4 children in the container.
var checkFull = function() {
if ($container.children().length === 4) {
$container.trigger('divFull');
}
}
$('#button1').click(function(){
$container.append('<div class="element">some text</div>');
checkFull();
});
Here is the demo.

Categories