JQuery removing buttons dynamically - javascript

I am adding buttons based on an array. The problem I am having is that every time I add another name to the array, it prints out all the buttons not just the one I added. I am wondering how would I erase all the old buttons before I add the array of buttons.
Here is my code
socket.on('usernames', function(data){
console.log(data);
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
// $users.html(html);
});
Below is an image. Test is the name of the first button and every time I add a new button it prints the entire array again. Is there a way to delete the old buttons?

Use the empty() method before you loop:
socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for (i = 0; i < data.length; i++) {
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($contentWrap);
}
});
Also note that you can improve performance and tidy the code by creating a single HTML string and setting the html() property to only require one DOM call. Try this:
socket.on('usernames', function(data){
var html = data.map(function(value) {
return '<input type="button" value="' + value + '"/></br>'
}).join('');
$('#contentWrap').html(html);
});

You can call .empty() on the parent element before appending the elements again.
$("#contentWrap").empty();
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}

Related

Trying to use FOR loop inside of the string. (Js, jQuery)

I have this code:
$.each(data, function(i,v){
$('#user-grid').append(
'<a href="my_urls">' +
'<div>' + v.points + '</div>' +
'<div>' + v.other + '</div>' +
'</a>'
);
});
Into the user grid div, I append the string with the values taken from data.
v.points and v.other are the numbers.
To this moment, everything works just fine. But what I need is to embed the for loop into the divs. In the places where I have v.points and v.other I want to put two simular FOR loops.
for(var i = 0; i < v.points; i++) {
//here is the html line that should be passed to the div, where v.points are now
<div>This is the point</div>
}
And almost the same for the v.other. Only with another line that should be pasted.
So basically how can I do that? I was trying to paste this loops right inside the "append()" but that didn't work out. I was also trying to create a variable inside of the loop and pass it in to the append, but got only one result, instead of all that I have needed.
I'm not sure if this is what are you looking for, this code prints 5 "This is your point" and 3 "This is your other" inside the anchor.
var data = [
{
points: 5,
other: 3
}
]
function printPoints(vPoints){
var str = "";
for(var i=0; i<vPoints; i++) {
str+="<div>"+"This is your point"+"</div>";
}
return str;
}
function printOther(vOther){
var str = "";
for(var i=0; i<vOther; i++) {
str+="<div>"+"This is your other"+"</div>";
}
return str;
}
$.each(data, function(i,v){
$('#user-grid').append(
'<a href="my_urls">' +
printPoints(v.points)+
printOther(v.other)+
'</a>'
);
});
See it on action here

Using a for loop within innerHTML

I want to add a box with individual boxes inside it with every age when the function is run. I tried doing it by splitting the innerHTML and using the for loop on just the agebox section so it will loop and create a new age box each time and not create a whole outerbox as well everytime like if you try loop the entire thing. I thought this would work but now it creates an age box for each loop but its placed outside the outer box and i cant figure out how to get it to loop within the outer box. If i remove the loop and just create one innerHTML then the age boxes i made manually are inside the outer box so im assuming theres a problem with the actual splitting up of the innerHTML. Thanks in advance!!
function Age(gender){
if (gender!==undefined){
el1 = document.getElementById('userdata');
el1.innerHTML += gender +"<br>";
}
el1 = document.getElementById('farespage');
el1.innerHTML += "<div id=\"outerbox\">";
for(var i=13; i<=18; i++){
el1.innerHTML +="<div class=\"agebox\" onclick=\"Relationship('"+i+"')\">"+i+"</div>";
}
el1.innerHTML += "</div><button type=\"button\" onclick=\"goback('Gender')\">back</button>";
}
You need to store the output content as a string and then append it to the DOM. Otherwise, the div will be auto-closed.
el1 = document.getElementById('farespage');
output = "<div id=\"outerbox\">"; //initialize output string
//build output string
for(var i=13; i<=18; i++){
output +="<div class=\"agebox\" onclick=\"Relationship('"+i+"')\">"+i+"</div>";
}
output += "</div><button type=\"button\" onclick=\"goback('Gender')\">back</button>";
el1.innerHTML = output; //output to DOM
View Fiddle
The line
el1.innerHTML += "<div id=\"outerbox\">";
is actually producing
<div id="outerbox"></div>
because most browsers will auto-close the HTML tags.
You should write all your HTML into a string buffer then append it with one big call; for example:
function Age(gender){
if (gender!==undefined){
el1 = document.getElementById('userdata');
el1.innerHTML += gender +"<br>";
}
el1 = document.getElementById('farespage');
// Magic begins here
var yourHTML = "";
yourHTML += "<div id=\"outerbox\">";
for(var i=13; i<=18; i++){
yourHTML +="<div class=\"agebox\" onclick=\"Relationship('"+i+"')\">"+i+"</div>";
}
yourHTML += "</div><button type=\"button\" onclick=\"goback('Gender')\">back</button>";
el1.innerHTML += yourHTML;
}
This has the added benefit of only touching the DOM once and not 7 times (which is generally a good thing).

Jquery-Mobile: Append the data to the non-native select option menu

I have a problem with adding the data to non-native select option menu on Jquery Mobile. Here's my code :
in html :
<select id="my-select" data-native-menu="false"></select>
in javascript :
var len = results.rows.length;
var s = '';
for (var i=0; i<len; i++){
$('#my-select')
.html($("<option></option>")
.attr("value",results.rows.item(i).id)
.text(results.rows.item(i).name));
}
So, if i delete the "data-native-menu="false"", that code is works perfectly. Whats wrong with my code ?
Thank you
You need to tell jQM to refresh/rebuild the widget any time you change the options within the selectmenu:
http://api.jquerymobile.com/selectmenu/#method-refresh
$('#my-select').selectmenu( "refresh", true );
FYI. by using html($("")...) within the for loop, you are overwriting the all options each time. Instead, use .empty() to clear existing options before the loop, and use append() to add the new ones.
To make it more efficient, create a string of all options and append them to the DOM once after the loop:
var opts = '';
for (var i=0; i<len; i++){
opts += '<option value="' + results.rows.item(i).id + '">' + results.rows.item(i).name + '</option>';
}
$('#my-select').empty().append(opts).selectmenu( "refresh", true );

Iterate over specific CSS-id's with jQuery

I'm making an image gallery in which I want the user to be able to click on a thumbnail and get a bigger image displayed.
This is the php-code to iterate over all images in a directory on the server and display them and give them each a unique id.
echo '<div id="image' . $i . '" class="image">' . $thumbsrc . '</div>';
echo '<div id="bigimage' . $i . '" class="bigimage">' . $imagesrc . '</div>';
This works fine, I use
$(".bigimage").hide();
to hide the bigger images.
So what I could do now is this:
$("#image1").click(function() {
$("#bigimage1").show();
});
$("#bigimage1").click(function() {
$("#bigimage1").hide();
});
But I find for up to 30 pictures I can't write 30 instances of this so I wanted to loop it.
I tried
for (var i = 1; i < 30; i++) {
$('#image' + i).click(function() {
$('#bigimage' + i).show();
});
$('#bigimage' + i).click(function() {
$('#bigimage' + i).hide();
});
}
Which doesn't seem to work? Why not?
If I do
for (var i = 1; i < 10; i++) {
$('#image' + i).append('<p>test' + i + '</p>');
}
it appends paragraph's to every #image-element so looping selector's seem to work.
How would I do this?
Thanks beforehand.
That's because all of your click handlers use the same value, for understanding what happens, you can refer to this question: Javascript infamous Loop issue?
Since your elements have classes, you can use you classes instead. index method returns the index of the passed element in a collection. After getting the index, for selecting the corresponding element in another collection you can use the eq method.
var $img = $('.image');
var $bigImg = $('.bigimage').hide();
$img.on('click', function() {
var i = $img.index(this);
$bigImg.eq(i).show();
});
$bigImg.on('click', function() {
// this keyword refers to the clicked element
$(this).hide();
});

Dynamic HTML table with Javascript checkboxes puzzle - how to access checkbox.checked from outside of the function?

Before I begin, I should mention I am using Javascript but I'm not using JQuery.
I have a function which obtains data from a site and displays it in an HTML table.
I would like to add a checkbox to each row, and find if each one has been checked or not later (i.e. when a button is clicked), outside of the function that creates the table.
The reason for this is that the function that makes the table only runs once and can't check if the box is checked or not (the user hasn't had a chance to check any yet!).
Each checkbox relates to other data displayed on the same row, which I can access outside of _cb_findItemsAdvanced(root) by declaring the 'items' variable before the function begins. However, I can't seem to do this for checkboxes.
I can add normal checkboxes to the table with:
"<input type=checkbox...".
However, I can't seem to access them from outside of the function that makes the table (and calls for the data). I've tried:
document.form1.sharedCheckboxName
It didn't seem to work.
I have tried everything, from creating a global checkbox array and trying to specify
" + checkbox[i] + "
instead of
"<input type=checkbox...",
but it didn't work. I know my current code has just specified a variable of type checkbox, rather than what I want which is to populate the table with my existing, global, array of checkboxes.
Any help would be greatly appreciated, as I am lost! I hope you're not, after reading that! :-)
Here is my code:
var items;
var checkbox = [];
function _cb_findItemsAdvanced(root)
{
items = root.findItemsAdvancedResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><form name="form1"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
checkbox[i] = document.createElement('input');
checkbox[i].type = "checkbox";
checkbox[i].name = "name";
checkbox[i].value = "value";
checkbox[i].id = "id" + i;
if (null != title && null != viewitem)
{
html.push('<tr><td>' + '<img src="' + pic + '" border="0">' + '</td>' +
'<td>' + title + '</td>' + '<td> <input type = "' + checkbox[i].type + '" + </t></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
if (checkbox[0].checked)
{
alert("HI"); //but nothing happens
}
since you are using html string forget about the checkboxes array.
your form should wrap the table not the other way around.
give your form an id
<form id="form1">
get the form and find all checkboxes
function findCheckedItems() {
var checkedItems = [];
var form = getElementById('form1');
var inputs = form.getElementsByTagName("input");
var checkboxIndex = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type.toLowerCase() === 'checkbox') {
if (inputs[i].checked) {
var data = item[checkboxIndex];
checkedItems.push(data);
// do whatever you like with the data
}
checkboxIndex++;
}
}
return checkedItems;
}

Categories