jquery dynamic click function - javascript

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
});

Related

Create a button to control the JavaScript create some elements. Then if any of these element changes, do something

I'd like to create a button using HTML. If user click the button, then use javascript to create some elements (like checkboxes). After these, if any of the elements changes, do something, like printing out some text.
Following is my code.
HTML:
<button id="try" type="button">TRY</button>
<div id="boxes"></div>
<p id="demo"></p>
Javascript:
doit = function(){
var checkboxes = "";
for(var i = 0;i<5;i++){
checkboxes += "<input type='checkbox' name='a'/>Option" + i+"<br>";
}
$("#boxes").html(checkboxes);
}
$('#try').click(function(){
doit();
})
$("input[name='a']").on("change",function(){
$("#demo").text("success!")
})
I really can't figure out where I am wrong. Demo:https://jsfiddle.net/slfan/cu7tn64o/12/.
Since you are dynamically adding new elements, you need to use a delegate event handler:
$(document).on("change", "input[name='a']", function() {
$("#demo").text("success!")
})
Updated JSFiddle: https://jsfiddle.net/cu7tn64o/14/

Refer to element ID set dynamically through 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]")

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

jquery append result the list of input button cannot get exact value

I append random list of button <input type="button" /> with different value of id's for the uniqueness which come from loop generated something look like this:
for(i=1;i<=10;i++){
var btn_list = '<input type="button" id="btn_id'+i+'" value="button#'+i+'">';
$('.btn_tableform').append(btn_list);
}
and the result of this forloop are 10 button with the name of button1 and so on... but my problem is i cannot get the correct value and my button click doesn't seems to work.
for(i=1;i<=10;i++){
$('#btn_id'+i).on('click',function(){
alert($(this).val());
});
}
You should create an HTML string and append that all at once after the loop. Also use a common class so you only need 1 handler!
var buttonList = "";
for(i=1;i<=10;i++){
buttonList += '<input type="button" id="btn_id'+i+'" class="button-list" value="button#'+i+'">';
}
$('.btn_tableform').append(buttonList);
$(".button-list").click(function() {
alert(this.value);
});
You click event won't work because your button aren't present on page load, they are create with your loop. You will need to use the jquery .on()instead of click() like so :
$(".button-list").on('click', function () {
alert($(this).val());
});

JQuery - Button triggers multiple times

I have a checklist, where I get a list when I click on a Checkbox. I can check more than one Checkbox - so I get more lists. I add at then end of each list a button, through JQuery. My Code for the button looks like this:
//Add a button to the previous list:
function add() {
$(".list:last").append("<div id='button'><input type='button' class='click' id='feld' name='feld' value='+'/>Add new listfield</div>");
}
When I click on the button, I get a new Checkbox with empty Textfield:
$(document).ready(function() {
// Variables for counting
var utxtname = 0;
var ucheckname = 0;
var utxtid = 1;
var ucheckid = 1;
var uctxtname = 1;
var uccheckname= 1;
//Function for the buttons with the same class ".click"
$(document).on('click', '.click', function() {
var utxtname ='utxtfield'+uctxtname;
var ucheckname ='uchecklist'+uccheckname;
$(this).closest(".list").append("<br><input type='checkbox' name=' "+ucheckname+"' id='"+ucheckid+"' checked><input type='textfield' name ='"+utxtname+"' id='"+utxtid+"'/>");
uctxtname += 1;
uccheckname += 1;
utxtid += 1;
ucheckid += 1;
});
});
My Problem:
When I generate more than one Button, the function triggers multiple times. If I have 3 lists with 3 generated buttons, my function generates 3 buttons if I click on a button. I knew the reason for my mistake. It's because I have 3 buttons with the same class, so it triggers the function multiple times. I just can't figure out how I can solve this problem. I tried so many methods to prevent this. For example unbind the function and bind it again. I also tried to dynamically add button with unique functions, but I couldnt get this.
Any Ideas how can I solve this problem easier?
Use inner function is the simplest solution, but may lead to a memory leak. This is just a more choice.
function add() {
var $button = $("<div id='button'><input type='button' class='click' id='feld' name='feld' value='+'/>Add new listfield</div>");
$(".list:last").append($button);
$button.click(function(){
/*process here*/
});
}
Just for remind, the button may not release , since click function is bound. If you remove in your own code, please add $("button").unbind("click");
Just use Off() in jquery before the on() statement
You can use
e.PreventDefault();
statement to prevent multiple trigger.

Categories