JQuery dynamically added button, text not in button - javascript

When I attempt creating buttons from jQuery, the text appears outside of the button element I created. I've tried creating each button individually and as a group, and neither method seems to work. What am I doing wrong?
<div id = 'output_div'></div>
var main = function(){
var selections = ['derp', 'herp', 'merp', 'foo'];
//individually creating each button
for(var i = 0; i < selections.length; i++){
$('#output_div').append("<input type='button'>" + selections[i] +
"</input>");
};
$('#output_div').append('<br><br>');
//buttons all created at the same time
var group_buttons = '';
for(var i = 0; i < selections.length; i++){
group_buttons += ("<input type='button'>" + selections[i] + "</input>");
};
$('#output_div').append(group_buttons);
};
$(document).ready(main);
https://jsfiddle.net/fjr56Lsj/4/

Another way to create a button using jquery would be as follows:
var dynamicButton = $('<button/>', {
text: selections[i],
id: 'dynamicButton_'+i
});
$('#output_div').append(dynamicButton);

Set the button text either as the value attribute of the <input>, or render the buttons as <button>:
$(function() {
var selections = ['derp', 'herp', 'merp', 'foo'];
for (var i = 0; i < selections.length; i++) {
$('#output_div').append("<input type='button' value='" + selections[i] + "' />");
};
$('#output_div').append('<br><br>');
for (var i = 0; i < selections.length; i++) {
$('#output_div').append("<button>" + selections[i] + "</button>");
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output_div'></div>

As input type button attribute , use value = selections[i] (keep Ur quotes careful)😉 else use button tag instead input element

The Button can be created in this fashion too:
$('<button/>', {
text: selections[i]
})
var main = function() {
var selections = ['derp', 'herp', 'merp', 'foo'];
//individually creating each button
for (var i = 0; i < selections.length; i++) {
$('#output_div').append($('<button/>', {
text: selections[i]
}));
};
$('#output_div').append('<br><br>');
};
$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output_div'>
</div>

Related

How to attach click event on dynamically appended inner elements?

I have a series div elements appended to a parent div.
Attaching click event binds on parent element.
var element = "";
for (var j = 0; j < 10; j++) {
element = element + "<div class='aClass'>"+j+"</div>";
}
$(".wrapper").append(function() {
return $(element).click(foo);
});
function foo() {
alert("index of element is:");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>
I need to know which appended div is clicked.
You can use the index() method
var element = "";
for (var j = 0; j < 10; j++) {
element = element + "<div class='aClass'>j</div>";
}
$(".wrapper").append(function() {
return $(element).click(foo);
});
function foo() {
alert("index of element is:"+$(this).index());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>
To get a reference to the element which raised the event use the this keyword in the event handler. To retrieve its index, you can use jQuery's index() method.
Also note that your logic can be made more succinct by appending all the HTML in one operation and using a single delegated event handler. Try this:
var elements = (new Array(10)).fill('<div class="aClass">j</div>');
$(".wrapper").append(elements).on('click', '.aClass', function() {
console.log(`index of element is: ${$(this).index()}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>
You can append and attach an event on every iteration instead of at the end.
for (let j = 0; j < 10; j++) {
const element = $("<div class='aClass'>j</div>");
element.click(() => foo(j));
$(".wrapper").append(element);
}
function foo(index) {
alert("index of element is: "+index);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>
If you're using jquery and you want to append a bunch of <div>s to a wrapper and have a click event on each, instead of creating a brand new event for each of those <div>s I would use event delegation and attach the event to the parent $('.wrapper'), then catch the event in the children. It would be something like this.
for (var j = 0; j < 10; j++) {
$('.wrapper').append($(`<div class="aClass">${ j }</div>`));
}
$('.wrapper').on('click', function(e) {
const target = $(e.target);
if (target.hasClass('aClass')) {
console.log(target.index());
}
});
function foo() {
alert("index of element is:" + $(this).text() + "-" + $(this).index());
}
var element = "";
for (var j = 0; j < 10; j++) {
element = element + "<div class='aClass'>j</div>";
}
$(".wrapper").append(function() {
return $(element).click(foo);
});
function foo() {
alert("index of element is:" + $(this).text() + "-" + $(this).index());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>
You can use an anonymous function to pass this object to the function so that you can use .index() to find the position:
var element = "";
for( var j = 0; j < 10; j++){
element = element + "<div class='aClass'>"+j+"</div>";
}
$(".wrapper").append(function() {
return $(element).click(function() {foo(this)});
});
function foo(el){
console.log("index of element is:", $(el).text() + ' at index ' + $(el).index());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>
You can append() inside the loop. And wrap foo inside wrapper and pass it to click.
var element = "";
const wrapper = $(".wrapper");
for(let j = 0; j < 10; j++){
element = "<div class='aClass'>j</div>";
wrapper.append(function() {
return $(element).click(() => foo(j));
});
}
function foo(index){
alert("index of element is:" + index);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>

How do I create different button for each item in an array / JavaScript

Here's my code:
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML = "<button>" + never[i] + "</button>";
}
}
I have a button in my HTML that invokes this function but it only creates a button for the last item (7). How can I create a different button for each one of the items in the array? Any help is appreciated.
The best way is to append created buttons in container.Each by each
var never = [1,2,3,4,7];
function please () {
var more=document.getElementById("more");
for (var i = 0; i < never.length; i++) {
var butt=document.createElement("button");
butt.innerHTML=never[i];
more.appendChild(butt);
}
}
By appending to innerHTML instead of assigning, like
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML += "<button>" + never[i] + "</button>";
}
}
please();
<div id="more">
</div>

How do I display an array inside a string in javascript?

This is the code :
list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
$("body").append("<p> list[i] </p>');
};
Look at the for loop(yes this is using jquery),i want to add the list items inside the paragraph headers.How do i do it ?
list[i] is not a string, it's a variable. To include it into the appended element, close the quotation marks in following way:
var list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
$("body").append("<p>" + list[i] + "</p>")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

how to display information underneath a specific button using javascript

I have the following piece of code I am working on. My purpose is to be able to grab information about different users from a specific website, display the name and other info and then have a button that when clicked, prints more information. I am able to get the information and display the name and picture, but when I click the button the information is displayed at the top of the page, not under the specific button that was clicked. I want for the information to be display under each user... I am new to Javascript and learning on my own, any help is appreciated!
function getUsers(user) {
var out = "";
var i;
for (i = 0; i < user.length; i++) {
out += '' + user[i].login + '<br>'+'</br> <img src="'+user[i].avatar_url+
'" alt="Image" style="width:304px;height:228px"</br></br>'+
'<button onclick=printRepos("'+user[i].repos_url+'")>Repositories</button></br>'+'<div id="id"></div>';
}
document.getElementById("id01").innerHTML = out;
}
Printing Function
function printF(array) {
var out = "";
var i;
for (i = 0; i < array.length; i++) {
out += array[i].id+'</br>';
}
document.getElementById("id").innerHTML = out;
}
This works fine. I just made div with dynamic ids and passed it to the function
function getUsers(user) {
var out = "";
var i;
for (i = 0; i < user.length; i++) {
out += '' + user[i].login + ' <br>'+'</br> <img src="'+user[i].avatar_url+
'" alt="Image" style="width:304px;height:228px"</br></br>'+
'<button onclick=printRepos("'+user[i].repos_url+'","'+i+'")>Repositories</button></br>'+'<div id="'+ 'id' + i +'"></div>';
}
document.getElementById("id01").innerHTML = out;
}
function printRepos(array, id) {
var out = "";
var i;
for (i = 0; i < array.length; i++) {
out += array[i].id+'</br>';
}
console.log('id' + id);
document.getElementById('id' + id).innerHTML = out;
}
Add the "this" keyword as a parameter to your onclicks, to pass in the button that was clicked:
<button onclick=printRepos(this,"'+user[i].repos_url+'")>Repositories</button>
Then locate the next div after that button in your event handler:
function printF(btn, array) {
var out = "";
var i;
for (i = 0; i < array.length; i++) {
out += array[i].id+'</br>';
}
// find the div
var d = btn; // start with the button
while (d.tagName != "DIV") d = d.nextSibling; // look for the next div
d.innerHTML = out;
}

Changing radio buttons name using Javascript

I'm using a simple JS duplicate function to duplicate a div. Inside is form information with radio buttons, including one group called 'getOrRequest'. Each div represents a book and needs to have its own 'getOrRequest' value.
The name needs to be changed in order to make each duplicated group of radio buttons selectable without affecting every other radio button. What is the best way to change these values?
Here is how I'm duplicating the div, in case that is the issue.
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
bookInfo.appendChild(copyDiv);
I then have tried a couple methods of changing the name value. Like this:
bookInfo.copyDiv.getOrRequest_0.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
bookInfo.copyDiv.getOrRequest_1.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
As well as this:
bookInfo.copyDiv.getOrRequest_0.name = 'getOrRequest' + idNumber + '[]';
bookInfo.copyDiv.getOrRequest_1.name = 'getOrRequest' + idNumber + '[]';
getOrRequest_0 and getOrRequest_1 are the ID's of the input values, but I've tried it a few ways now and nothing seems to work. Thanks in advance!
EDIT: MORE INFO
Here is the specific code I'm using:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = 'addListing' + idNumber;
for(var j = 0; j < size; j++){
if(copyDiv.childNodes[j].name === "getOrRequest[]"){
copyDiv.childNodes[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
And it just doesn't seem to work.. The divs are duplicating, but the name value is not changing.
You can try this - http://jsfiddle.net/ZKHF3/
<div id="bookInformation">
<div id="addListing">
<input type="radio" name="addListing0[]" />
<input type="radio" name="addListing0[]" />
</div>
</div>
<button id="button">Add Listing</button>
<script>
document.getElementById("button").addEventListener("click", AddListing, false);
var i = 1;
var bookInfo = document.getElementById('bookInformation');
function AddListing() {
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = "listing" + i;
for ( var j = 0; j < size; j++ ) {
if ( copyDiv.childNodes[j].nodeName.toLowerCase() == 'input' ) {
copyDiv.childNodes[j].name = "addListing" + i + "[]";
}
}
bookInfo.appendChild(copyDiv);
i++;
}
</script>
The trouble is you are looking for child nodes of the div, but the check boxes are not child nodes, they are descendant nodes. The nodes you are looking for are nested within a label. Update your code to look for all descendant inputs using copyDiv.getElementsByTagName("input"):
var idNumber = 0;
function addAnotherPost() {
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
var inputs = copyDiv.getElementsByTagName("input");
for(var j = 0; j < inputs.length; j++){
if(inputs[j].name === "getOrRequest[]"){
inputs[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
http://jsfiddle.net/gilly3/U5nsa/

Categories

Resources