Sort by id element using jQuery [duplicate] - javascript

This question already has answers here:
How to sort DOM elements while selecting in jQuery?
(4 answers)
Closed 9 years ago.
I have this code:
<li id="pi_div2"></li>
<li id="pi_div5"></li>
<li id="pi_div4"></li>
I need to sort like this:
<li id="pi_div2"></li>
<li id="pi_div4"></li>
<li id="pi_div5"></li>
My script now:
<script>
$("li[id*=pi_div]").sort(function(a,b) {
if(a.id < b.id) {
return -1;
}
else {
return 1;
}
}).each(function() { console.log($(this).attr("id"));});
</script>

Based upon your original html, you could do something like this:
Html:
<ul id="cat">
<li id="3">Text 3</li>
<li id="1">Text 1</li>
<li id="2">Text 2</li>
</ul>
JavaScript:
$("#cat li").sort(function (a, b) {
return parseInt(a.id) > parseInt(b.id);
}).each(function () {
var elem = $(this);
elem.remove();
$(elem).appendTo("#cat");
});
Check out this fiddle.
EDIT:
As #KiKo has correctly pointed out, the above code breaks if you have a list longer than ten elements. You can fix this by replacing the "greater than" in the sort function with a minus.
Html:
<ul id="cat">
<li id="3">Text 3</li>
<li id="2">Text 2</li>
<li id="1">Text 1</li>
<li id="9">Text 9</li>
<li id="11">Text 11</li>
<li id="5">Text 5</li>
<li id="7">Text 7</li>
<li id="6">Text 6</li>
<li id="12">Text 12</li>
<li id="4">Text 4</li>
<li id="10">Text 10</li>
<li id="8">Text 8</li>
</ul>
JavaScript:
$("#cat li").sort(function(a, b) {
return parseInt(a.id) - parseInt(b.id);
}).each(function() {
var elem = $(this);
elem.remove();
$(elem).appendTo("#cat");
});
Here's a new JSFiddle.

Here is a solution.
HTML:
<div class="initial">
<ul id="cat">
<li id="3">Text 3</li>
<li id="1">Text 1</li>
<li id="2">Text 2</li>
</ul>
</div>
<div class="new"></div>
JavaScript:
First, find out how many list items there are. Then go through each one, in order, and add it to a string that you eventually print out on screen.
var size = $('#cat > li').size()
var string = '<ul>';
for(var i = 1; i<=size; i++){
string = string.concat('<li>' + $('#'+i+'').html() + '</li>');
}
string = string.concat('</ul>');
$('.new').html(string);

Related

How can I get number from each id and append to another data attribute using jquery?

I have some listings.
Currently id is test_3, test_1, test_2. I need number (3,1,2) from id of each li and append this number in to another data attribute. Please check the result section. It will give you an idea about what I am expecting. Thanks
Html
<ul id="cat">
<li id="test_3">Text 3</li>
<li id="test_1">Text 1</li>
<li id="test_2">Text 2</li>
</ul>
Script
$('#cat').attr('id').split("-")[2];
Expected result
<ul id="cat">
<li id="test_3" data-id="3">Text 3</li>
<li id="test_1" data-id="1">Text 1</li>
<li id="test_2" data-id="2">Text 2</li>
</ul>
To achieve this you can loop over the li elements and set the data() based on the number in the id attribute. Try this:
$('#cat li').each(function() {
$(this).data('id', this.id.split('_')[1]);
}).click(function() {
console.log($(this).data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="cat">
<li id="test_3">Text 3</li>
<li id="test_1">Text 1</li>
<li id="test_2">Text 2</li>
</ul>
You can loop through all of the children of the ul element with the id cat.
On each loop, get the ID by getting the id attribute, splitting it on _ and getting the first index.
You can then set the attribute by using JQuery's attribute function, which you can learn more about here.
$('#cat li').each(function () {
var dataId = $(this).attr('id').split('_')[1];
$(this).attr('data-id', dataId);
});
An example of this in action
$('#cat li').each(function () {
var dataId = $(this).attr('id').split('_')[1];
$(this).attr('data-id', dataId);
});
console.log($('#cat').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="cat">
<li id="test_3">Text 3</li>
<li id="test_1">Text 1</li>
<li id="test_2">Text 2</li>
</ul>
This should some your problem.
Using $(this).attr("id").split('_') will split "cat_3" into "cat" and "3" then using [1] after will select "3"
$("#cat li").each(function(){
$(this).attr("data-id", $(this).attr("id").split('_')[1]);
})
console.log($("#cat").html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="cat">
<li id="test_3">Text 3</li>
<li id="test_1">Text 1</li>
<li id="test_2">Text 2</li>
</ul>
You can also use a RegExpression.
var suffix = "test_2".match(/\d+/); // results --> 2
Basically it fetches out numeric value within a string value.
Usage
$('#cat li').each(function() {
$(this).data('id', this.id.match(/\d+/));
})

jquery onclick parent remove child action

Actually I'm really very sorry about my question, I'm not sure how to make attention or ask question about this kind of problem.
Please see my code 1st.
<div data-model="ABC123" id="product">Select a Product</div>
<ul id="lists">
<li data-product="P1">Product 1
<ul id="sublists">
<li data-item="it1">P1 Item 1</li>
<li data-item="it2">P1 Item 2</li>
<li data-item="it3">P1 Item 3</li>
<li data-item="it4">P1 Item 4</li>
</ul>
</li>
<li data-product="P2">Product 2
<ul>
<li data-item="it1">P2 Item 1</li>
<li data-item="it2">P2 Item 2</li>
<li data-item="it3">P2 Item 3</li>
<li data-item="it4">P2 Item 4</li>
</ul>
</li>
<li data-product="P3">Product 3</li>
<li data-product="P4">Product 4</li>
</ul>
<div id="codes">
<span class="code1"></span>
<span class="code2"></span>
<span class="code3"></span>
</div>
The jquery code is:
<script>$('#product').click(function () {
var pmodel = $(this).data('model');
$('.code1').empty().append(pmodel);
$('.code2').empty();
$('.code3').empty();
});
$('#lists li').click(function () {
var dmodel = $(this).data('product');
$('.code2').empty().append(dmodel);
});
$('#lists li ul li').click(function () {
var item = $(this).data('item');
$('.code3').empty().append(item);
});</script>
You may directly view this at http://codepen.io/alshedupur/pen/YqKGqV
Everything is work fine, but my problem is, when I trigger parent list item like: Product 1 / Product 2 / Product 3
In result I want to empty .code3 span
I try to use $('.code3').empty(); on 2nd action but if I use this, then 3rd action I mean sub list click function not work.
Please see my screenshot for clearly understand what I want:
You need to empty .code3 as well.
$('#product').click(function() {
var pmodel = $(this).data('model');
$('.code1').empty().append(pmodel);
$('.code2').empty();
$('.code3').empty();
});
$('#lists > li').click(function(e) {
e.stopPropagation();
var dmodel = $(this).data('product');
$('.code2').empty().append(dmodel);
$('.code3').empty();
});
$('#lists li ul li').click(function(e) {
e.stopPropagation();
var item = $(this).data('item');
var dmodel = $(this).parents("li").data('product');
$('.code2').empty().append(dmodel);
$('.code3').empty().append(item);
});
#product:hover,
li:hover {
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-model="ABC123" id="product">Select a Product</div>
<ul id="lists">
<li data-product="P1">Product 1
<ul id="sublists">
<li data-item="it1">P1 Item 1</li>
<li data-item="it2">P1 Item 2</li>
<li data-item="it3">P1 Item 3</li>
<li data-item="it4">P1 Item 4</li>
</ul>
</li>
<li data-product="P2">Product 2
<ul>
<li data-item="it1">P2 Item 1</li>
<li data-item="it2">P2 Item 2</li>
<li data-item="it3">P2 Item 3</li>
<li data-item="it4">P2 Item 4</li>
</ul>
</li>
<li data-product="P3">Product 3</li>
<li data-product="P4">Product 4</li>
</ul>
<div id="codes">
<span class="code1"></span>
<span class="code2"></span>
<span class="code3"></span>
</div>

Looping through .find() results and gathering .text()

I've got the following code:
jQuery
$("li").click(function(){
$(this).toggleClass("selected");
$(".selected").each(function(){
$(".items").append(this.text() + ", ");
});
});
html
<ul class='category'>
<h4>Category</h4>
<li class="selected">Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li class="selected">Link 4</li>
<li class="selected">Link 5</li>
<li>Link 6</li>
<li>Link 7</li>
</ul>
<span class="items">Selected Items Appear Here</span>
I'm trying to search the contents of the $(".category") for tags with the .selected class before appending the results to another div.
This is the result I'm hoping for:
<span class="items">Link 1, Link 4, Link 5</span>
However, the this.text() seems to be returning an undefined error.
Any clue as to what I'm doing wrong?
You need to call .text() on a jQuery object, and since this refers to the element (see jQuery docs for .each()), simply wrap this in $() to make a new jQuery object of the current element in the loop.
example:
$(".items").append($(this).text() + ", ");
in saying this, you'd probably be better off simply using .innerHTML unless you want the jQuery object for other reasons.
example:
$(".items").append(this.innerHTML + ", ");
You can try something like
var $lis = $(".category li").click(function() {
//toggle the current li's selected class
$(this).toggleClass("selected");
setItems();
});
//set the initial value
setItems();
function setItems() {
//get the texts of all selected `li`'s text to an array
var texts = $lis.filter(".selected").map(function() {
return $(this).text();
}).get();
//set the array values to the `.items` element
$('.items').text(texts.join())
}
.selected {
background-color: lightgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h4>Category</h4>
<ul class='category'>
<li class="selected">Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li class="selected">Link 4</li>
<li class="selected">Link 5</li>
<li>Link 6</li>
<li>Link 7</li>
</ul>
<span class="items">Selected Items Appear Here</span>
js fiddle example for you
**Jquery**
$(function () {
$("li").click(function () {
$(this).toggleClass("selected");
appendItems();
});
function appendItems() {
var selecteditem = "", lement, appementElement = ", ";
lement = $(".selected").size();
$(".selected").each(function (index) {
if ((lement - 1) == index) {
appementElement = "";
}
selecteditem = selecteditem + ($(this).text() + appementElement);
});
$(".items").html("").append(selecteditem);
}
});
html
<ul class='category'>
<h4>
Category</h4>
<li class="selected">Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li class="selected">Link 4</li>
<li class="selected">Link 5</li>
<li>Link 6</li>
<li>Link 7</li>
</ul>
<h3>
<span class="items"></span>
</h3>
i hope this may hep you
I think you confused Javascript's this with jQuery's $(this). $() is the jQuery constructor function. this is a reference to the DOM element of invocation.
Please find the working code below:
$("li").click(function(){
$(this).toggleClass("selected");
$(".selected").each(function(){
$(".items").append($(this).text() + ", ");
});
});
$(".selected").each(function(){
$(".items").append($(this).text() + ", ");
});
.selected{
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='category'>
<h4>Category</h4>
<li class="selected">Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li class="selected">Link 4</li>
<li class="selected">Link 5</li>
<li>Link 6</li>
<li>Link 7</li>
</ul>
<span class="items">Selected Items Appear Here</span>
Read up on this: jQuery $(this) vs Javascript this

Tabs and content into Array

I have two tabs like in this example:
<div id="tabs">
<ul>
<li>me</li>
<li>you</li>
</ul>
<div id="tabs-1">
<ul id="sortable1" class="connectedSortable ui-helper-reset">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
</div>
<div id="tabs-2">
<ul id="sortable2" class="connectedSortable ui-helper-reset">
<li class="ui-state-highlight">Item 5</li>
<li class="ui-state-highlight">Item 6</li>
<li class="ui-state-highlight">Item 7</li>
<li class="ui-state-highlight">Item 8</li>
<li class="ui-state-highlight">Item 9</li>
</ul>
</div>
</div>
I want to turn all of it into array's : me=>1,2,3,4,5 you=>5,6,7,8,9 any ideas? Thought maybe sortable1< li.index and give every li id but how to connect it with tab? Little help would be nice.
var obj = {};
$('#tabs > ul li a').each(function(i,ele) {
obj[$(ele).text()] = $.map($('li', $(ele).attr('href')), function(k, i) {
return $(k).text();
});
});
FIDDLE
var meid = $("#tabs a:contains(me)").attr("href");
var youid = $("#tabs a:contains(you)").attr("href");
var me = $("li", $(meid)).map(function() { return $(this).text() });
var you = $("li", $(youid)).map(function() { return $(this).text() });
The guys provided much more succinct answers. I didn't use $.map but here's what I wrote (might be useful for someone):
var tabs = $("#tabs");
var firstUL = tabs.first("ul");
var akeys = firstUL.find("a");
var valueDivs = tabs.children("div");
var dictionary = {};
$.each(akeys, function(index, value) {
var key = $(value).text();
dictionary[key] = $(valueDivs[index]).find("li");
});
//now dictionary contains all the <li> elements organized by the names in the first ul
//the beauty of JavaScript's dynamic features:
alert($(dictionary.me[0]).text()); //this will show Item 1
alert($(dictionary["you"][4]).text()); //this will show Item 9

Adding level depth to class of nested lists

I have nested lists like this:
<ul>
<li>item 1</li>
<li>item 2
<ul>
<li>subitem 1</li>
<li>subitem 2</li>
<ul>
<li>sub-subitem1</li>
</ul>
</li>
</ul>
</li>
<li>item 3
<ul>
<li>subitem 1</li>
</ul>
</li>
</ul>
Is there any way I could add a class to the based on their depth level so the output is something like this?
<ul class="level-0">
<li>item 1</li>
<li>item 2
<ul class="level-1">
<li>subitem 1</li>
<li>subitem 2</li>
<ul class="level-2">
<li>sub-subitem1</li>
</ul>
</li>
</ul>
</li>
<li>item 3
<ul class="level-1">
<li>subitem 1</li>
</ul>
</li>
</ul>
I am new to jQuery, have tried this:
$("ul").each(function(index, element){$(element).attr("class", "level-" + index);});
...but it only counts the ul's based on their index. Any help is much appreciated!
Try this:
$('ul').each(function() {
var depth = $(this).parents('ul').length;
$(this).addClass('level-' + depth);
});
See http://jsfiddle.net/alnitak/YSZFm/
If you only have 3 levels, try this:
$('ul').addClass('level-0');
$('ul').find('ul').removeClass('level-0').addClass('level-1');
$('ul').find('ul').find('ul').removeClass('level-0').removeClass('level-1').addClass('level-2');
http://jsfiddle.net/fallen888/2rATE/
For a more dynamic solution, try this:
$("ul").each(function(index, element) {
var parents = $(this).parents('ul');
var level = -1;
if (parents.length > 0) {
var parentClass = $(parents.get(0)).attr('class');
level = parseInt(parentClass.substr(parentClass.indexOf('level-') + 6, 1));
}
$(this).addClass('level-' + (level + 1));
});
http://jsfiddle.net/fallen888/2rATE/1/

Categories

Resources