jQuery, count number of dynamicly added <li> in <ul> - javascript

I have a list of LI in a UL, they are all dynamically added via jQuery. I am trying to alert the number of LI in this list. Right now I can only get it to alert 0. I think it is because its trying to count the original number on load? here is my code and fiddle:
https://jsfiddle.net/ts7Lwbfs/1
<ul id="list">
<li>original</li>
</ul>
var familly = []
familly.push('<li>1</li>');
familly.push('<li>2</li>');
familly.push('<li>3</li>');
familly.push('<li>4</li>');
$('#list').prepend(familly);
$('#list').on('click', 'li', function(ev){
var howMany = $('#list').length;
alert(howMany);
});
How can I get it to alert the total number of LI after they are dynamically added?

The selector $('#bet_slip') matches an element with the ID bet_slip, and as ID's are unique jQuery doesn't expect there to be more than one, and as none of your elements have that ID, you get zero?
Seems like what you want is to count the number of LI's in the #list list
$('#list').on('click', 'li', function(ev){
var howMany = $('#list li').length;
alert(howMany);
});
FIDDLE
Note that this counts all LI's currently present, including the one that was there originally.

If you are trying to find only the count of newly added li ( excluding the original ) , you can filter the li and exclude the first one using :not:first expression.
$('#list').on('click', function(ev){
var howMany = $(this).find('li:not(:first)').length;
alert(howMany);
});
https://jsfiddle.net/DinoMyte/ts7Lwbfs/4/

You can count the total number of list items this way:
$('#list').on('click', function(){
var howMany = $('#list li').length;
alert(howMany);
});
To get the number of added list items, first capture the count of original list items before you add new ones, and then subtract the total in your function from the original count.
var originalCnt = $('#list li').length;
$('#list').prepend(familly);
$('#list').on('click', function(){
var howMany = $('#list li').length - originalCnt;
alert(howMany);
});
Fiddle Demo

Related

Populating ul list with index

I am having trouble populating a ul li with its index value.
My HTML below.
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
My JS below.
$('document').ready(function(){
var indexus = $('li').index();
$('li').each(function(){
$('li').html(indexus);
});
});
JS Fiddle: http://jsfiddle.net/kuJWc/407/
I want to populate the li with its appropriate li index value, but I can only end up getting the index value of the latest (in this case 3). How would I go about looping in each index value so that each li shows the value of its own index number?
you should do like this:
$('li').each(function(){
$(this).html($(this).index());
});
you were adding the index to all the li.. so istead of $(this) inside of the each, you were using $('li'). which adds the last value li index to all of them.
Try this:
$('document').ready(function(){
$('li').each(function(){ // iterate through each `li`
var $li = $(this); // get the current `li` element
var index = $li.index(); // get the current `li` index
$li.html(index); // set the `li`'s html to the index value
});
});
I added some comments to help you understand what each step does, I hope that helps!
What about this:
$('document').ready(function(){
var indexus = $('li');
for (var i = 0; i <= indexus.length; i++) {
$(indexus[i]).html(i);
}
});
Here it works.
You can get an array of the ul's children and then iterate over each of the children with something like this:
var arr = $('ul').children();
for (var i = 0; i < arr.length; i++){
$(arr[i]).html(i);
}

creating 'n' no. of list items on user input through "prompt()"

I wan't to replace a list item of an unordered list and generate 'n' list items in its place after clicking on it (n is input by the user on prompt when a list item is clicked).
I referred to the following link, but still couldn't make out a solution for my case:
Generating list item x number of times, based on user input
This is what I tried but its not working:
HTML:
<ul id="list" onclick="inputNumber()">
<li>list-1</li>
<li>list-2</li>
<li>list-3</li>
</ul>
CSS:
li {
list-style: none;
display: inline;
}
JavaScript:
function inputNumber() {
var index = $(this).index();
// to record the index of the clicked item
var inputNum = prompt("Divide By:");
// input and store 'n' by the user
var oldList = document.getElementById("list");
// the main old list
var garbage= oldList.removeChild(oldList.childNodes[index+1]);
// remove the clicked item from the main list
var newList=document.createElement("li");
// create new list item
var i;
for (i=1;i<=inputNum;i++)
{
list.append(newList.clone().text('list-'+i));
// loop to clone and append 'n' list items in place of the previous one
}
}
JSfiddle :
https://jsfiddle.net/yoshi2095/k0jt8n7x/44/
Please help. Thanks.
edit:
only the 'clicked' item should get replaced by the 'n' items input by the user at the same place of that 'clicked' item. Other list items should remain at their respective places as before.
JSFiddle
There were a few issues you had in your code. One was you were forgetting $() around functions that were only for jQuery. You also were not removing the child elements correctly, the jQuery functions $(this) and .remove() and JavaScript .children together work to remove only the clicked element. You were also only creating one new element to add to the list, but you needed to create multiple, so I added that inside the for loop.
$("li").click(function() {
var inputNum = prompt("Divide By:");
var oldList = document.getElementById("list");
for (var i=1;i<=inputNum; i++)
{
var newList=document.createElement("li");
$(this).parent().append($(newList).text('list-'+i));
}
$(this).remove();
});

jQuery - loop through ol with li containing tables, and get data from table columns

I have an unordered list (ul) whose list item (li) elements each contain a table with 2 columns (first column is a delete button (attribute 'data-id' contains the id of the data), second column is the data text). I need to get the values inside the table of each li and add the values to a hidden field for processing on the server. How would I go about retrieving the values from the table inside the li. I know how to loop through the ul itself and pull out each li...
$('#ol li').each(function (i, li) {
var listItem = li;
// Get data from table within li here
});
but I am not sure how to proceed after this step. Thank you for any help.
EDIT
Here is an example of what gets appended to the ol.
$('#ol').append("<li><table><tbody><tr><td style='padding-right:16px'><button type='button' class='btn btn-danger remove' data-id='" + item.val() + "'><b>X</b></button></td><td>" + txt + "</td></tr></tbody></table></li>");
SOLUTION
Using find() I was able to locate the desired elements and extract the values.
$('#ol li').each(function () {
var id = $(this).find('td').first().find('button').attr('data-id');
if(id == -1)
{
var txt = $(this).find('td').last().text();
$('#hf').val($('#hf').val() + txt + "|");
}
else
{
$('#hf').val($('#hf').val() + id + "|");
}
});
Thank you to those who assisted.
You should read up on the usage of the this keyword.
So, when you run a function like this -
$('#ol li').each(function(){
$(this).val() //returns the value of the current li that is being looped through
});
The way the .each() function works is the same way as a loop, so it goes through every #ol li element one at a time, and you utilize this to access the current element that is being looped through.
So now, from here, you can search for the required children. You will most likely also have to utilize jquery's .data() function to get the information stored in the data-id attribute.
https://api.jquery.com/jquery.each/
https://api.jquery.com/jquery.data/
You could get the two columns of the data like so:
$('#ol li').each(function (i, li) {
var listItem = li;
var column1 = $(li).find("td").first().text();
var column2 = $(li).find("td").last().text();
// do things with columns
});
I'm assuming you just have a 2x1 table with a simple text value in each.

Hide same elements in a list

I have a problem I want to solve with jQuery. In a list, I want to check if two items have the same text, and if so I want to delete the second one.
I am not really sure how to go about it.
The markup is simple, kinda like this
<ul>
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
I cannot use an active/inactive class because this list is dynamic and I don't know in advance how it's going to be populated.
Any idea?
$.inArray for a tmp array would work.
$(document).ready(function(){
var tmparr = [];
$('.list li').each(function(i,item){
if($.inArray($(this).text(), tmparr) >= 0){
$(this).remove();
}else{
tmparr.push($(this).text());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
You can achieve this e.g. like this:
var unique = {};
$('li').each(function() {
var txt = $(this).text();
if (unique[txt])
$(this).remove();
else
unique[txt] = true;
});
Fiddle
As explanation: unique is initialized as object. While each() iterates over all li elements, the if (unique[txt]) is true in case it was previously set to true for the text of the li currently processed. In this case the current li will be removed. If not, unique[txt] for the text of the current li is set to true and added to unique. As it might not be clear what unique finally contains: { Text1=true, Text2=true, Text3=true, Text4=true }
You will need to iterate over your li elements and store their text in an array. If the text for the ith element is already in the array, skip it. Once you have an array of unique text strings, remove all li elements and generate new ones from the information in your array.
http://jsfiddle.net/k255o52e/1/
$('ul li').each(function () {
var txt = $(this).text();
// finds all LI that contain the same text
// excludes the first element
var $li = $('li:contains("' + txt + '"):not(:first)');
// and removes the other
$li.remove();
})
UPDATE:
$('ul li').each(function () {
var txt = $(this).text();
var $li = $('li:contains("' + txt + '"):not(:first)').filter(function(index)
{
return $(this).text() === txt;
});
$li.remove();
})

How to find number of <ul> inside each div

I have a large file of this form [similar div's throughout]. I want to be able to select a div, find the number of ul's in it and traverse through each of them to get value of each li in it.
<div class="experiment">
<div class="experiment-number">5</div>
<ul class="data-values">
<li><div></div> 14</li>
<li><div></div> 15</li>
</ul>
<ul class="data-values">
<li><div></div> 16</li>
</ul>
</div>
I have tried looping through all experiment divs, then select the uls, but it selects all the ul in the page, not only the ones under current div.
$('experiment ul').eq('$i');
Your HTML is currently incorrect, since you're simply starting new <div> and <ul> elements rather than closing the existing ones. Ignoring that because it's trivial to fix, we'll move on to the real issue.
You need to select all of the <div class="experiment"> elements, then iterate through them. To do that you can use the .each() function. It might look something like this:
var experiments = $('.experiment'); // all of them
experiments.each(function(i, val) { // will iterate over that list, one at a time
var experiment = $(this); // this will be the specific div for this iteration
console.log("Experiment: " + experiment.find('.experiment-number').text());
// outputs the experiment number
console.log("Experiment ULs: " + experiment.find('ul').length);
// number of <ul> elements in this <div>
var total = 0;
experiment.find('ul.data-values li').each(function() {
total += parseInt($(this).text(), 10);
});
console.log("Experiment total: " + total);
// outputs the total of the <li> elements text values
});
Take a look at this jsFiddle demo.
to get all the ul inside div.experiment
var ul = $('.experiment').find('ul');
and to get all li elements inside each ul found above
ul.each(function(list) {
var li = $(list).find('li');
});
$('.experiment').each(function() {
var cnt = $(this).children('ul').length;
$(this).find('.experiment-number').text(cnt);
});
First of all you need to work out the correct selector for each DIV.
The selector you want is:
".experiment"
Notice the . to denote a class selector.
This will allow you access to each DIV element. If you then want to loop though each of these, you can do so like this:
$(".experiment").each(function(){
var div = $(this);
var elementsInThisDiv = div.find("ul");
//you now have a list of all UL elements in the current DIV only
var numberOfElements = elementsInThisDiv.length;
//you now have a count of UL elements belonging to this DIV only
//you can loop the UL elements here
$(elementsInThisDiv).each(function(){
var ul = $(this);
//do something with the UL element
//like get the LI elements...
var liElements = ul.find("li");
});
});
IMPORTANT: There is also an error with your HTML, you need to close your <ul> elements correctly using </ul>

Categories

Resources