This is my jsfiddle
http://jsfiddle.net/1ty1v8u1/5/
If an element is clicked on twice , how can i achieve toggle behavior for that particular div ?
If i click on office twice in the jsfiddle how to make it open and close ??
This is my code
function showRestaurantDetailsByLocation(response,locationname)
{
$('.restListings').remove();
$('.addNewRestaurant').remove();
var ulhtml = $('<ul class="restListings"></ul>');
var divhtml = $('<div class="inner-intit"><sub class="sub">Your Favorite Area</sub></div>');
divhtml.append('<br>');
var $newbutton= $('<input/>').attr({ type: 'button', location:locationname , name:'btn1', class:'btn btn-success addNewRestaurant', value:locationname});
for(var i=0;i<response.length;i++)
{
divhtml.append('<li><h6>'+response[i].area+'</h6><p>'+response[i].address+'</p><span id="delete" class="inDelete inDeleteSub"></span></li>');
}
divhtml.append($newbutton);
ulhtml.append(divhtml);
$("#"+locationname).append(ulhtml);
}
You are appending the new elements on click. Just check for previously appended element in same div. If it exist then simply remove it, if not then add new:
$(document).on('click', '.lielement', function() {
var locationname = $(this).attr("id");
if($(this).find('.restListings').length)
$(this).find('.restListings').remove()
else
displayingRestaurantByArea(locationname);
});
Working Demo
Related
I dynamically create a table full of links of 'actors', which allows to pull the actors information into a form to delete or update the row. The delete button only pops up when you select an actor.
I'm able to click a row, pull the information into the forms, and delete it on first try. However when I attempt to add a new 'Actor' and then delete it, or just delete an existing 2nd row, the button 'Delete Actor' doesn't work. It's only after the first successful delete does the button no longer work.
var addActor = function() {
// Creates a table of links for each added actor with an id based from # of actors
$("#actorsTable").append("<tr><td><a href='' onclick='deleteActor(this)' class='update' data-idx='" + actors.length + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");
$(".update").off("click");
$(".update").on("click", selectActor);
};
var deleteActor = function(e) {
$("#deleteActor").on('click', function(event) {
event.preventDefault();
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
});
};
I'm new to jQuery/javascript, and I'm pretty sure its due to the change in DOM, but I just don't know what to change to make it work.
Here is an Example of it in action
Try
var deleteActor = function(e) {
$("#deleteActor").unbind();
$("#deleteActor").on('click', function(event) {
event.preventDefault();
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
});
};
Here is the link for unbind.
http://api.jquery.com/unbind/
The problem is because you're adding another click handler (in jQuery) within the click handler function run from the onclick attribute. You should use one method or the other, not both. To solve the problem in the simplest way, just remove the jQuery code from the deleteActor() function:
var deleteActor = function(e) {
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
};
when you add html dynamically you need to attach the event to the parent static element like so:
$("#actorsTable").on("click","a.update", function() {
$(this).closest("tr").remove();
});
I am creating a dynamic list of tasks that appear after the input is written and input's length is less or equal 30 characters and the button is pressed.
Together with the task there is a trash icon created.
I want to enable the user to remove chosen task when he clicks on the icon which comes from the external library ionicons.
I have an issue that when the trash icon is clicked, it removes this Li and all Li elements that were created after that clicked Li.
I am prepending li elements to the list.
Here's the snippet:
$('#addNewTaskBtn').click(function () {
var inputText = $('#dayTask').val();
var trashIcon = '<i class="ion-trash-b"></i>';
var newTask = $('<li />', { html: inputText + " " + trashIcon });
// clearing the input after click
$('#dayTask').val('');
if (inputText.length && inputText.length <= 30)
$(newTask).prependTo('ul.dayList');
$('.ion-trash-b').click(function () {
$(newTask).remove();
});
});
My question is:
How to remove only the one Li element which trash icon is clicked, and not all Li element (including the one) that were created later?
Thank you very much for your help.
$('.ion-trash-b').click(function(){
$(this).parent().remove(); // or $(this).closest("li").remove();
});
or even assign it onload to attach to all future trash icons using event delegation
$(function() {
$("#listContainer").on("click",".ion-trash-b",function(){
$(this).parent().remove();// or $(this).closest("li").remove();
});
});
where listContainer is the ID of the UL
Remove the closest li of the clicked ion-trash-b and as your elements are dynamically generated, use event delegation for ion-trash-b click event like following.
$('#addNewTaskBtn').click(function () {
var inputText = $('#dayTask').val();
var trashIcon = '<i class="ion-trash-b"></i>';
var newTask = $('<li />', { html: inputText + " " + trashIcon });
// clearing the input after click
$('#dayTask').val('');
if (inputText.length && inputText.length <= 30)
$(newTask).prependTo('ul.dayList');
});
$('body').on('click', '.ion-trash-b', function () {
$(this).closest('li').remove();
});
I have the code below:
$(document).ready(function(){
var counter = 0;
$("button").click(function() {
$('body').append("<button>generate new element "+(counter++)+"</button>")
});
});
JSFiddle
When you click duplicated button, it won't duplicate another button again besides the original button only works.
Why cannot listen this event to duplicated buttons?
EDITED:
//Click button event DELEGATION
$(document).on("click",".choice", function() {
var userChoice = $(this).attr("value");
//EXTERNAL SPAGUETTHI CODE
};
Need to grab "value" of this button when it's clicked.
You need delegation: catching the clicks on the parent but only those that were made on button elements. $("button") selects the existing buttons on the page, $(document) (you can replace document with your button container) will select the container and by using $(document).click("button", ...) you delegate the clicks on the buttons.
$(document).ready(function() {
var counter = 0;
$(document).click("button", function(e) {
var value = $(e.target).attr("data-value"); // or .data("value")
alert(value);
$('body').append("<button data-value=\"" + ++counter + "\">generate new element " + counter + "</button>")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-value="initial-button">generate new element</button>
Here are some other similar answers I posted:
Direct and delegated events
Delete dynamic elements
Function not working second time
I have a form with an HTML table that has a button (#addRows) that when clicked will clone the first table row and append it to the bottom of the table.
This table resides in a section of HTML with some other input fields that can also be cloned and appended onto the bottom of my form. When I am cloning the section I am changing all child element ID's to include a number that can be iterated dependent on how many times the user clones the section.
Example
<div id="someID"> ... </div>
<div id="someID2"> ... </div>
<div id="someID3"> ... </div>
I am doing this with JQuery like this
$(function() {
var $section = $("#facility_section_info").clone();
var $cloneID = 1;
$( ".addSection" ).click(function() {
var $sectionClone = $section.clone(true).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + $cloneID); });
$('#facility_section_info').append($sectionClone);
$cloneID++;
});
});
When I clone the section that holds the table I am also cloning the #addRows button which when clicked should append a table row to the table it is being clicked on. However if I clone my section and I click on my second `#addRows button it will clone my table row but it is appending to my first table and not the second.
Here is my addRows button and event handler
<input type="button" value="+" id="addRows" class="addRows"/>
$(function() {
var $componentTB = $("#component_tb"),
$firstTRCopy = $("#row0").clone();
$idVal = 1;
$(document).on('click', '.addRows', function(){
var copy = $firstTRCopy.clone(true);
var newId = 'row' +$idVal;
copy.attr('id', newId);
$idVal += 1;
copy.children('td').last().append("Remove");
$componentTB.append(copy);
});
});
My question is, when I clone my section of HTML that holds my table and #addButton how can I ensure that when the user clicks on the original button it will clone and append to that table or if I click the cloned button it will clone and append to the cloned table only?
If anything is unclear please let me know so I can try to better explain what I am trying to do, thanks.
Here is a JSFiddle demonstrating the problem I am having.
Because I truly love you BigRabbit, here is where I got to. You will see at least one useful fix here:
var $sectionClone = $section.clone(true);
$sectionClone.find("*[id]").andSelf().each(function () {
$(this).attr("id", $(this).attr("id") + $cloneID);
});
and a fix for an issue you did not report yet
$copy.children('td').last().append(' Remove');
using
$("#facility_section_info").on('click', '.remove', function (e) {
e.preventDefault();
$("#"+$(this).data("removeid")).remove();
});
FIDDLE
$(function () {
var $componentTB = $("#component_tb"),
$firstTRCopy = $("#row0").clone(),
$section = $("#facility_section_info>fieldset").clone(),
$cloneID = 0,
$idVal = 0;
$("#facility_section_info").on('click', '.remove', function (e) {
e.preventDefault();
$("#"+$(this).data("removeid")).remove();
});
$("#facility_section_info").on('click', '.addRows', function () {
$idVal++;
var $copy = $firstTRCopy.clone(true);
var newId = 'row' + $idVal;
$copy.attr('id', newId);
$copy.children('td').last().append(' Remove');
$(this).closest("fieldset").find("tbody").append($copy);
});
$("#facility_section_info").on("click", ".addSection", function () {
$cloneID++;
var $sectionClone = $section.clone(true);
$sectionClone.find("*[id]").andSelf().each(function () {
$(this).attr("id", $(this).attr("id") + $cloneID);
});
$('#facility_section_info').append($sectionClone);
});
});
the app receive a n html dive and create a page and append it to the app
I bind all link-buttons in set of pages to one function
which will do different tasks depends on the id of the page
now I have a problem when a page has more than one link-button
I need the ID of the clicked button
Html:
<a id="x">x </a>
<a id="y">y </a>
Js:
var btns = [];
$('#page-' + newpages[j].pageID + ' a').each(function () {
btns.push({
id: this.id,
value: this.value,
name: this.name
});
});
for (i in btns) {
$('#' + btns[i].id).bind('click', function () {
test(btns[i].id)
});
// bin all buttons in current page to test()
}
};
};
function test(x) {
var page = $('.ui-page-active').attr('id');
/////////
//here I'm trying to ge the ID of clicked button of that page (each ID means something)
var pos = '';
$('#' + page + ' a').click(function () {
//Get the id of this clicked item
var BID = $(this).attr("id");
alert(BID);
send(BID);
});
Why don't you just bind to the click event on each button independently? If you switch by ID anyway why go through a generic function, any shared functionality can be abstracted into a function and utilized by each click handler so you loose nothing.