Refer to element ID set dynamically through Javascript - javascript

I am setting the ID of an element, say a button, dynamically. An example is given below (the code may have syntactic errors, I am merely trying to explain my problem).
function myFunc(){
var counter = 0;
return function(){
counter += 1;
var rowContent = '<div>';
rowContent += '<button type="button" class="btn btn-default" id="button"' + counter + '></button>';
rowContent += '</div>';
$('#someElement').append(rowContent);
};
}
Now I want to associate a click event with the button. I need to mention the ID element when associating the event with the button (e.g. $('#myID')). But since the ID is being set dynamically, I do not know for sure what the ID may be. Could someone tell me how I could refer to the dynamically-set ID of the element when associating an event with it? Thanks in advance!!

Delegate the event to the parent element rowContent.
$('#someElement').append(rowContent);
$('button', rowContent).on('click', function(e) {
// button element in the 'rowContent' context
}
Delegating it to #someElement will also work, unless you'll be putting multiple buttons with different click handlers inside of there.

You should better be using event delegation in such case:
$('#someElement').on('click','[id^=button]',function(){
//do stuff
});

You can easily define your own custom attribute and select it with this attribute as:
rowContent += '<button type="button" mybtn="" class="btn btn-default" id="button"' + counter + '></button>';
and here is the selector:
$("div[mybtn]")

Related

jquery dynamic click function

Can some one help me?
The Idea is to create dynamic buttons with a loop and then use the jquery click function to use one of them
//I'm creating dynamic buttons like this:
for(i=0; i<1000; i++){
$contentBox.append('<button id="add'+ i +'" type="button" class="btn btn-success">Accept</button>');
//but how would I create the jquery click function?
$('#add'+i).click(function(e) {....});
//this does not create 1000 click functions. It only changes the id to the last one so what ever button you click on you will always get the las id
}
#Spencer's comment is on point - you can use a delegated event. Or, you can simply use the button class:
for(i=0; i<1000; i++){
$contentBox.append('<button id="add'+ i +'" type="button" class="btn btn-success">Accept</button>');
//Rest of your code
}
//Then attach the event to the class:
$('button.btn-success').click( function(){
//I suspect you'll want the ID so here goes
var buttonID = $(this).attr('id');
//The rest of the fun stuff
});
If you put i in the .... of your click handler, it won't fix its value to what it was when the click handler was created; rather it will always refer to the variable i which takes the value 1000 when you're done looping. Perhaps you could store i in an attribute of the button like below (or read it out of the element's id).
$contentBox = $('#content');
$result = $('#result');
for(i=0; i<10; i++){
$contentBox.append('<button id="add'+ i +'" data-eyeVal="' + i + '" type="button" class="btn btn-success">Accept</button>');
//but how would I create the jquery click function?
$('#add'+i).click(function(e) {$result.append('<br/>clicked ' + $(this).attr('data-eyeVal'))});
//this does not create 1000 click functions. It only changes the id to the last one so what ever button you click on you will always get the las id
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<div id="result"></div>
You should use live function for dynamic button click events. try this
$('#add'+i).live("click", function(){
// codings
});

Accessing dynamically appended div elements in jQuery

I need a suggestion on below scenario.
I have an object of items and dynamically building a html object as follows:
$.each(item,function(k, iteminner) {
html += '<td><div id="outerdiv">' + iteminner.Name + '</div>';
html += '<div id="clickme"></div></td>';
});
A table is built in this format, where each box will contain a name and button in each td. When a user clicks on a button of a cell I want to show the name respectively.What is it that I am missing here?
$('#clickme").click() {
alert($("#outerdiv").iteminner.name);
}
Assuming that id is unique for both the divs, like id="outerdiv" + k , how do I access element present in second cell, when second div id="clickme" + 2 is clicked?
ID's they have to UNIQUE
// Use class instead
$.each(item, function(k, iteminner) {
html += '<td><div class="outerdiv">' + iteminner.Name + '</div>';
html += '<div class="clickme"></div></td>';
});
// You need to have event delegation here as a direct onclick wont be binded for the dynamically created .clickme
$(document).on("click", ".clickme", function(){
// You need to fetch the html of .outerdiv, so traverse to it first.
var _html = $(this).closest("td").find(".outerdiv").html();
alert(_html);
});
Firstly you are appending multiple elements with the same id to the DOM, which is invalid. You should change your HTML to use classes, like this:
$.each(item, function(k, iteminner) {
html += '<td><div class="outerdiv">' + iteminner.Name + '</div><div class="clickme"></div></td>';
});
From there you need to use a delegated event handler on the .clickme elements (as they are dynamically created after the DOM has loaded) to traverse the DOM and find their sibling .outerdiv. Try this:
$(document).on('click', '.clickme', function() {
var name = $(this).siblings('.outerdiv').text();
// do something with name here...
});
Note that I used document as the primary selector above. Ideally you should use the nearest static parent element - I would suggest you use the same selector you use to append the html variable to.

Variable Interpolation in Jquery code inside for loop

I have some code, http://jsfiddle.net/hucw940s/
which has a for loop.
before
<div id="container">
</div>
after
for (i = 1; i < 4; i++){
var showMe = $('<a href=# id="link' + i + '">')
.append('click').click(function(){ alert('You clicked num: ' + i) });
$('#container').append(
$('<div id="div'+i+'">').append('this is div number: ' + i).append(showMe)
);
}
so the links are generated with id=link1, link2, link3 etc, and the divs appended are the same, however the onclick code seems to put the var i in after the event, so on clicking any link they say "you clicked number 4"
How can I make this use the i from the clicked link inside the function that is called on click?
What you are experiencing is the expected behavior based on your code.
However, what you are actually trying to do is pass in event data to your click function. This can be accomplished like this:
for (i = 1; i < 4; i++) {
var showMe = $('<a href=# id="link' + i + '">').append('click')
.click({value: i}, function (e) { alert('You clicked num: ' + e.data.value) });
$('#container').append($('<div id="div' + i + '">').append('this is div number: ' + i).append(showMe));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
</div>
First, you have to assign the event data, so we pass in an object
{value: i} before we pass in the handler function.
Then, in the handler function, we assign the variable e to the
event, so we can access the data attribute.
Finally, you access the value that was passed in by referencing
e.data.value.
You can add as many event data objects as you want and reference them by name this way.
The reason your code is not working as you are expecting is because the variable i is already equal to 3 by the time the click event happens, since the for loop completes before you are able to click any of the links.
Hope this helps give you a better understanding of why your code is behaving the way it is and what you can do to fix it.
Store the id in a data-attribute.
Updated jsFiddle

Inject JavaScript variable as value in anonymous function

I have a form where I add inputs dynamically. When I add a new input I increment a global id variable and concatenate it to the input's id so it will be unique. I also create a delete button for each input that should remove that input and himself (through removing the container <div> they are in). I do the remove process by adding an anonymous function to the delete button's click event via JQuery:
$('#deletebutton' + id).click(function(){
$('#inputcontainer' + id).remove();
});
The only problem with this solution that it isn't work in the way I excepted it. When I click any of the delete buttons it will delete the last input container because when I click, it executes the anonymous function and evaluate the id variable at that time, so the selected id will be the last input's id. So always the last input container will be deleted.
Is there a way to rewrite this function so when I add it to the click event, than it will evaluate the id, inject it and handle the selection as if it had been written like #inputcontainer1, #inputcontainer2, etc.
I can make this by adding the function's body to the button's onclick() event:
var newbutton = '<button id="deletebutton' + id + '" type="button" onclick="javascript:$(\'#inputcontainer' + id + '\').remove();">x</button>';
But is there a way doing this with the JQuery click() way?
To answer the specific question, you'd have to dig the id out of the DOM:
$('#deletebutton' + id).click(function(){
var id = $(this).attr("id").replace('deletebutton','');
$('#inputcontainer' + id).remove();
});
You could also store it as data when you create the delete button:
<button data-id="1" id="deletebutton1">
$('#deletebutton' + id).click(function(){
var id = $(this).data("id");
$('#inputcontainer' + id).remove();
});
Note that in both of these cases, id is a string, not an integer.
When I click any of the delete buttons it will delete the last input container [...]
If your 1st snippet is inside a loop, id probably isn't being scoped to each iteration. So, by the time one of the click() events is triggered and it's trying to use .remove(), id will have already been set to the last value given while looping.
You can use an IIFE to create an additional function scope for keeping a different id for each iteration (ref: closure).
/* loop */ {
var id = ...;
(function (id) {
$('#deletebutton' + id).click(function(){
$('#inputcontainer' + id).remove();
});
})(id);
}
Though, for future reference, ECMAScript 6 is adding block scoping which should allow for:
/* loop */ {
let id = ...;
$('#deletebutton' + id).click(function(){
$('#inputcontainer' + id).remove();
});
}
$('#deletebutton' + id).click(function(){
$(this).parent().remove();
});
If the container isn't a direct parent and doesn't have a class you could do:
$('#deletebutton' + id).click(function(){
var idNum = $(this).attr("id").replace('deletebutton','');
$("#inputcontainer"+idNum).remove();
});
If you've got appropriate classes (or can add them), this would be best:
$(document).on("click",".deleteButton",function() {
$(this).parents(".inputContainer").remove();
});

javascript button click function not working

I have a website where user can select an item, the detail is then displayed, including the quantity. I have also included a button inside the div so that when clicked, it should decrease the quantity by 1.
$("#btnBuy1").click(function()
{
if (!sessionStorage['quantity1'])
{
sessionStorage['quantity1']=1;
}
else
{
sessionStorage['quantity1']++;
}
$("#dropbox").html('<div id = "1"><img class = "thumb" id = "t1" src="../images/birthday_metoyou.jpg" />' + teddy[1].desc + ", Price £"
+ teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "<button id = 'btnRemove1'>Remove</button></div><br/>");
updateBasket();
sessionStorage["total1"] = parseInt(sessionStorage.getItem('quantity1')) * teddy[1].price;
updateSubtotal();
if (Modernizr.sessionstorage)
{ // check if the browser supports sessionStorage
myids.push(teddy[1].partnum); // add the current username to the myids array
sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage
}
else
{
// use cookies instead of sessionStorage
}
});
$("#btnRemove1").click(function()
{
alert(remove);
});
I put in an alert message to see if the button is working properly, but when I click the btnRemove1 button, nothing happens.
Since the button is dynamically added, can you try:
$(document).on('click', '#btnRemove1', function() {
{
alert("remove"); //I dont know what remove was is the example, added quotes around it.
});
That is because the button is added later (dynamicly). You will have to use a delegate.
You don't have to use body for this. Any non dynamicly inserted element that is a parent of #btnRemove1 will do.
$('body').on('click','#btnRemove1',function(){
alert(remove);
});
The reason is that you bind the event before the element #btnRemove1 is present on your page. Therefore there is nothing to bind the event to. The body element however - will be present on the page and delegate your event to #btnRemove1.
You can either tie the event to the document (what jQuery live used to do before it was deprecated)
now it is:
$(document).on("click", "#btnRemove1", function(){})
or you can rebind the event after #btnRemove1 is added to the Dom.
Most likely, your Remove button isn't in the DOM before you try to attach the click event to it. It is hard to tell from your code snippets, but if the Buy button action hasn't completed successfully, then Remove won't exist.
At the point that you attach the click event to Remove, try console logging $("#btnRemove1").length to see if it exists, or use break points.
An improvement to your code would be to cache in a variable $("#dropbox") and then look for your buttons within it, as in:
var $dropBoxNode = $("#dropbox");
$dropBoxNode.find("#btnRemove1");
And you should use .on() instead of the deprecated .click().
Try putting the remove button click handler addition after you create the remove button
///Code snippit
$("#dropbox").html('<div id = "1"><img class = "thumb" id = "t1" src="../images/birthday_metoyou.jpg" />' + teddy[1].desc + ", Price £"
+ teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "<button id = 'btnRemove1'>Remove</button></div><br/>");
$("#btnRemove1").click(function()
{
alert(remove);
});
updateBasket();
///Code snippit
$('a.edit').on('click','a.edit',function(){
if (confirm("Are you sure you want to Edit this Photo?"))
{
....
....
}
});
Not Working When Data is Loading with AJAX on a DIV Area
Just Like
EDIT

Categories