I have <ul> like this:
<ul class="options" id="selt_count">
<li value="1">One</li>
<li value="2">Two</li>
<li value="5">Five</li>
<li value="12">Other</li>
</ul>
What I want is to get all values of <li> into variable in the following format (1,2,5,12) in jquery.
Thanks
How about:
var values = $('#selt_count li').map(function() {
return this.value
});
values; // [1, 2, 5, 12]
To get a string representation you can do:
var s = '(' + values.get().join(',') + ')'; // "(1,2,5,12)"
FYI the value attribute was deprecated a while ago.
References:
jQuery.map
Related
I have a simple list:
<ul id="list">
<li id="item-1">1</li>
<li id="item-2" style="display: none">2</li>
<li id="item-3">3</li>
<li id="item-4">4</li>
<li id="item-5">5</li>
</ul>
And need to get index of a specific item disregarding hidden items.
var list = document.getElementById('list');
var items = list.querySelectorAll('li:not([style*="display: none"])');
I try to convert NodeList in Array:
var list_items = Array.from(items);
But don't known how to run something like that: list_items.indexOf('item-3')
https://codepen.io/marcelo-villela-gusm-o/pen/RwNEVVB?editors=1010
You can make a function to find the id you need in a list you want, passing two parameters, that way you can use this function dynamically.
Based on id, inside the function just need to use .findIndex() that returns the index or -1 if not found.
See here:
var list = document.getElementById('list');
var items = list.querySelectorAll('li:not([style*="display: none"])');
var list_items = Array.from(items);
function getIndexById(idToSearch, list){
//ES6 arrow function syntax
return list.findIndex(elem => elem.id == idToSearch)
//normal syntax
//return list.findIndex(function(elem) {return elem.id == idToSearch})
}
console.log("found at index: ", getIndexById("item-3", list_items))
<ul id="list">
<li id="item-1">1</li>
<li id="item-2" style="display: none">2</li>
<li id="item-3">3</li>
<li id="item-4">4</li>
<li id="item-5">5</li>
</ul>
Not exactly related to the question, but if possible, I would suggest you to change your HTML to remove that inline style of display: none and change it to a class, (e.g: class='hidden'), it would be better for your .querySelector when using :not, for example: li:not(.hidden), since any space in your inline style can break your selector. ("display:none" != "display: none", spot the space)
Maybe like this:
var item = list_items.find(function(item) {
return item.id === "item-3";
});
I would recommend using :not(.hidden) instead of "grepping" for a match on the style tag. Then, simply find the index after casting the NodeList to an array.
For the Vue.js inclined, see this fiddle: https://jsfiddle.net/634ojdq0/
let items = [...document.querySelectorAll('#list li:not(.hidden)')]
let index = items.findIndex(item => item.id == 'item-4')
console.log('item-4 index in visible list is', index)
.hidden {
display: none;
}
<ul id="list">
<li id="item-1">1</li>
<li id="item-2" class="hidden">2</li>
<li id="item-3">3</li>
<li id="item-4">4</li>
<li id="item-5">5</li>
</ul>
Maybe you can use map. First you can create an object with id and value. Then use map function to create array of this object. Then you can access it with foreach, when id = 'item-3'.
I have a variable there is define few value with using JavaScript backtick. How can I use another variable with backtick?
var liElem = '';
$('button').click(function(){
var newData = 'This is new data'
liElem = `<ul>
<li class=" ' + newData + ' ">Good news</li>
<li class="icon-text-dark-yellow">Fair</li>
<li class="icon-text-dark-red">Poor</li>
<li class="icon-text-light-gray">N/A</li>
</ul>`;
console.log(liElem);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>click</button>
Why newData variable is not readable inside? JavaScript backtick? There is any way to do this?
Answer will be appreciated!
It is called template literals, as the documentation states:
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.
What you want to do is called expression interpolation what you can achieve with ${variableName}.
You need to use as the following:
const newData = 'This is new data';
const liElem = `<ul>
<li class="${newData}">Good news</li>
<li class="icon-text-dark-yellow">Fair</li>
<li class="icon-text-dark-red">Poor</li>
<li class="icon-text-light-gray">N/A</li>
</ul>`;
console.log(liElem);
I hope that helps!
Use placeholder ${<your var name>}
var liElem = '';
$('button').click(function(){
var newData = 'This is new data'
liElem = `<ul>
<li class=${newData}>Good news</li>
<li class="icon-text-dark-yellow">Fair</li>
<li class="icon-text-dark-red">Poor</li>
<li class="icon-text-light-gray">N/A</li>
</ul>`;
console.log(liElem);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>click</button>
This is not different from any regular string if you start a string with " you have to end it with ". So if you start it with ` then you need to end it with `.
So if you want to use + newData + then you have to write:
var newData = 'This is new data'
liElem = `<ul>
<li class=" ` + newData + ` ">Good news</li>
<li class="icon-text-dark-yellow">Fair</li>
<li class="icon-text-dark-red">Poor</li>
<li class="icon-text-light-gray">N/A</li>
</ul>`;
console.log(liElem);
Or as you already use tempalte string literals can use embedded expressions <li class="${newData}">
I think there may be a new way to sort them without an attribute
but I'm not getting it to work properly. Who can help me understand why?
Initially I create an array, I put the various elements in the correct order.
var order = [4,3,2,7,5,0,1,6,8];
var i = 0;
$.fn.formordina = function(selector){
(selector ? this.find(selector) : this).parent().each(function(){
$(this).children(selector).sort(function(){
return order[i++];
}).detach().appendTo(this);
});
return this;
};
$(".form-action ol").formordina('li');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div class="form-action">
<ol>
<li>banana</li>
<li>apple</li>
<li>tomato</li>
<li>kiwi</li>
<li>pear</li>
<li>peach</li>
<li>lemon</li>
<li>ginger</li>
<li>orange</li>
</ol>
</div>
This might help you some. If you have a specific Sort order you want for the list, you may want to pass it in as an Option. Then collect the Items, organize the, flush the current list, and replace them with the new order.
$.fn.formordina = function(options) {
console.log("Options", options);
var listItems = this.find(options.items);
var newList = {};
$.each(options.order, function(k, v) {
newList[k] = listItems.eq(v - 1)[0];
});
$(this).html("");
console.log(newList);
$(this).append(newList);
};
$(function() {
$(".form-action ol").formordina({
items: "> li",
order: [4, 3, 2, 7, 5, 0, 1, 6, 8]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div class="form-action">
<ol>
<li>banana</li>
<li>apple</li>
<li>tomato</li>
<li>kiwi</li>
<li>pear</li>
<li>peach</li>
<li>lemon</li>
<li>ginger</li>
<li>orange</li>
</ol>
</div>
Hope that helps.
I have the following tag in my html and I need to select the data-id value and the inner html value into an array.
How can I achieve this in either Jquery or Javascript
<li class="dual-listbox__item" data-id="1">Politieacademie</li>
<li class="dual-listbox__item" data-id="3">IBM</li>
<li class="dual-listbox__item dual-listbox__item--selected" data-id="5">Energias de Portugal</li>
You can use .map() along with .get() to convert it to basic array
var arr = $('li.dual-listbox__item').map(function() {
return {
id: $(this).data('id'),
text: $(this).html()
};
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="dual-listbox__item" data-id="1">Politieacademie</li>
<li class="dual-listbox__item" data-id="3">IBM</li>
<li class="dual-listbox__item dual-listbox__item--selected" data-id="5">Energias de Portugal</li>
</ul>
Select the elements, loop them using map and you got your array. Below will return an array of objects holding the data you want
const res = Array.from(document.querySelectorAll('.dual-listbox__item')).map(e => ({
dataId: e.dataset.id,
innerHTML: e.innerHTML
}));
console.log(res);
<li class="dual-listbox__item" data-id="1">Politieacademie</li>
<li class="dual-listbox__item" data-id="3">IBM</li>
<li class="dual-listbox__item dual-listbox__item--selected" data-id="5">Energias de Portugal</li>
You can use $('.dual-listbox__item').each() to achieve this:
var dataId = [];
var nHTML = [];
$('.dual-listbox__item').each(function(){
dataId.push($(this).data('id'));
nHTML.push($(this).text());
});
console.log(dataId);
console.log(nHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="dual-listbox__item" data-id="1">Politieacademie</li>
<li class="dual-listbox__item" data-id="3">IBM</li>
<li class="dual-listbox__item dual-listbox__item--selected" data-id="5">Energias de Portugal</li>
I have an array, it contains values [1,2].
I also have an html list
<ul>
<li id="1">List Item 1</li>
<li id="2">List Item 2</li>
<li id="3">List Item 3</li>
</ul>
I need to iterate through the array, and if a value in the array matches an ID in my list, add a class to the list item.
The output example would be
<ul>
<li id="1" class="active">List Item 1</li>
<li id="2" class="active">List Item 2</li>
<li id="3">List Item 3</li>
</ul>
I'm a bit lost on this one, thanks in advance!
Try to use $.map() to translate the array into "#1,#2" and pass it as a selector then add class to it,
var arr = [1,2]; // var arr = Express.completedSteps;
$($.map(arr,function(val,_){
return "#" + val;
}).join()).addClass('active');
DEMO
try
var arr=[1,2];
for(var i in arr){
$("#"+arr[i]).addClass("active");
}
DEMO
Try out following.
$(document).ready(function(){
var obj = [1,2,5,7];
$.each( obj, function( key, value )
{
$('li').each(function(){
if($(this).attr('id')==value)
{
$('#'+value).addClass( "active" );
}
});
});
})
try out the demo here.
demo