Ask for multiple id's with the same data attribute - javascript

I'm trying to check for a data attribute in multiple list items.
My HTML:
<ul id="year">
<li id="2006">2006</li>
<li id="2007">2007</li>
<li id="2008">2008</li>
<li id="2009">2009</li>
<li id="2010">2010</li>
<li id="2011">2011</li>
<li id="2012">2012</li>
<li id="2013">2013</li>
<li id="2014">2014</li>
</ul>
And this is the jQuery:
jQuery('#year li').click(function()
{
var year = jQuery(this).attr('id');
if ((jQuery(this).data('state') === undefined) || (jQuery(this).data('state') == "off"))
{
jQuery(this).data('state', 'on');
}
else
{
jQuery(this).data('state', 'off');
}
});
Now i am trying to check if there are any list items where the "state" == "on"
Like this:
if ((jQuery('#year li').data('state') == "on"))
But it does not seem to be working...
EDIT: So i tried all the different snippets you gave me: none of them worked so i made a simple for loop that looks in every list point itself:
for ( var y = 2006, l = 2015; y < l; y++ )
{
if ((jQuery('#year #'+y).data('state') == "on"))
{
alert('data found');
}
Another problem was that i didnt had any event before my code!
Thanks for the support!

the jQuery('#year li') will return an array of jquery objects.
you will need to loop each one
$('#year li').each(function () {
if ((jQuery(this).data('state') === "on")){
alert("on state found");
}
});

You can use .filter() then check length property
var list = jQuery('#year li').filter(function(){
return $(this).data('state') == "on";
//OR, using native dataset
//return this.dataset.state == 'on'
});
if (list.length){
//li with state on exits
}

The reason this doesn't work for you is that jQuery doesn't store data values in the "standard" element dataset. You can acheive your goal by doing that yourself:
$('#year li').click(function() {
this.dataset.state = this.dataset.state === 'off' ? 'on' : 'off';
if($('#year li[data-state="on"]').length > 0) {
alert('Found!')
}
});
#year li[data-state="on"] {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="year">
<li id="2006">2006</li>
<li id="2007">2007</li>
<li id="2008">2008</li>
<li id="2009">2009</li>
<li id="2010">2010</li>
<li id="2011">2011</li>
<li id="2012">2012</li>
<li id="2013">2013</li>
<li id="2014">2014</li>
</ul>

Related

how to apply active class using ng-class for list elements(mutli-select)?

I have a scenario,that I have static list elements,where I need to add active class using ng-class,when I click on list element,the active class would be added.
Here is my code:
vm.idArry = [];
vm.selectedFunc = function (item) {
item.selected = !item.selected;
if(vm.idArry.indexOf(item) == -1){
vm.idArry.push(item);
}
else {
var index = vm.idArry.indexOf(item);
vm.idArry.splice(index, 1);
}
}
Html:
<ul>
<li id="one"><a ng-class="{'active':item.selected}" ng-click="selectedrFunc(1)" ></a></li>
<li id="two"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(2)" ></a></li>
<li id="three"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(3)"></a></li>
<li id="four"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(4)" ></a></li>
<li id="five"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(5)"></a></li>
<li id="six"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(6)" ></a></li>
for the above code,I have to get append active class when I click on list elements(i.e; multiple list must be added active class when I clicked on multiple list elements).
Thanks in advance.
Any help would be appreciated.
Remove usage of item.selected and use following code:
<li id="one"><a ng-class="{'active': vm.idArry.indexOf(1) != -1}" ng-click="selectedFunc(1)" >A</a></li>
This checks for item existence in vm.idArray; Also remove item.selected on vm.selectedFunc
So your vm.selectedFunc should look like this:
vm.selectedFunc = function (item) {
if(vm.idArry.indexOf(item) == -1){
vm.idArry.push(item);
}
else {
var index = vm.idArry.indexOf(item);
vm.idArry.splice(index, 1);
}
}

Iterating a list of items and append () html if the text of the item corresponds to "something" (using jquery)

I have a list of items, and I would like:
if the text of an item corresponds to another text, then I have to add in a span with a class (class is an icon font).
<div id="block-system-main-menu">
<ul>
<li>Home</li>
<li>Mappe</li>
<li>Vulc</li>
<li>Equa</li>
<li>About</li>
</ul>
</div>
Strangely however adds the class to to all the items and I do not understand why ....
$('#block-system-main-menu li').each(function () {
if (($(this).children().text()) == 'Mappe' || 'Vulc' || 'Equa'){
$(this).append('<span class="fa fa-caret-right"></span>');
}
});
thanks
DEMO
Because your condition satisfies for all the scenarios. You need to separate the concern in or condition:
$('#block-system-main-menu li').each(function () {
var text=$(this).find('a').text(); //get the a's text using find and store it as
//reference in variable
if (text == 'Mappe' || text== 'Vulc' || text== 'Equa'){
$(this).append('<span class="fa fa-caret-right"></span>');
}
});
Please have a look at below snippet. You have to check for each text as follows:
$('#block-system-main-menu li').each(function () {
if (($(this).children().text()) == 'Mappe' || $(this).children().text() =='Vulc' || $(this).children().text() =='Equa'){
$(this).append('<span class="fa fa-caret-right"></span>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="block-system-main-menu">
<ul>
<li>Home</li>
<li>Mappe</li>
<li>Vulc</li>
<li>Equa</li>
<li>About</li>
</ul>
</div>
Hope this will be helpful
$('#block-system-main-menu li').each(function () {
var _getCondition =$(this).children().text()
if (_getCondition == 'Mappe' || _getCondition == 'Vulc' || _getCondition== 'Equa'){
$(this).append('<span class="fa fa-caret-right">Hello</span>');
}
});
Added hello in span just for validation
jsfiddle

jQuery find data attributes with one datakey and multiple values

I want to retrive all the objects with one datakey and multiple values, for QuickSand:
<ul>
<li data-company="Microsoft">Steve</li>
<li data-company="Google">Jobs</li>
<li data-company ="Facebook">Michael</li>
<li data-company ="Google">Richard</li>
<li data-company ="Facebook">Tim</li>
</ul>
How can i retreve all the li items with data-company Microsoft and Google (these two values are in a array) like this:
var itemes = $('ul').find('li[data-comapany={"Microsoft","Google"}]');
Thank you.
you could create an array of the required companies, and check for each li if the data is contained in that array:
var companies = ["Microsoft", "Google"];
$(function() {
var items = $('ul li').filter(function() {
return $.inArray($(this).data("company"), companies) > -1;
});
items.css({
"position": "relative",
"margin-left": "25px"
});
console.log(items);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-company="Microsoft">Steve</li>
<li data-company="Google">Jobs</li>
<li data-company="Facebook">Michael</li>
<li data-company="Google">Richard</li>
<li data-company="Facebook">Tim</li>
</ul>
You could filter it:
var itemes = $('ul').find('li').filter(function(){
return $(this).data('company').match(/Microsoft|Google/);
});
-DEMO-
To handle case for LI without any data-company set, you should use:
var itemes = $('ul').find('li').filter(function(){
var data = $(this).data('company');
return data ? data.match(/Microsoft|Google/) : null;
});
You can also combine selectors:
var items = $("[data-company*='Microsoft'], [data-company*='Google']");
jsFiddle
You could do it like this:
var companies = ['Google', 'Microsoft', 'Waffle House'];
companies.forEach(function(company, index) {
companies[index] = "li[data-company='" + company + "']";
});
$('ul').find(companies.join(',')).css('background', 'red');

js select hours for each day of the week

I am allowing a user to select hours for each day of the week through the use of lists. Visually the lists are just boxes with 1am, 2am, 3am, etc inside them and when clicked are highlighted to show they are 'selected'. To do this I add a class of 'hour-selected' to the li item.
I also need to keep track of what hours the user has clicked for each day (those with class 'hour-selected'. I know this logic works as I have used this code before, but only for one day. In this example, I need to show all days on the same page.
With a few changes to my original code I came up with this, but I feel there must be some optimization I could do to prevent the repeating js used to push selected hours in for each day, but I am out of ideas and thoughts to do this...
html : (this would repeat for each day of the week with id different for day)
<ol id="hour-select-mon" class="clearfix">
<li class="">12am</li>
<li class="">1am</li>
<li class="">2am</li>
<li class="">3am</li>
<li class="">4am</li>
<li class="">5am</li>
<li class="">6am</li>
<li class="">7am</li>
<li class="">8am</li>
<li class="">9am</li>
<li class="">10am</li>
<li class="">11am</li>
<li class="">12pm</li>
<li class="">1pm</li>
<li class="">2pm</li>
<li class="">3pm</li>
<li class="">4pm</li>
<li class="">5pm</li>
<li class="">6pm</li>
<li class="">7pm</li>
<li class="">8pm</li>
<li class="">9pm</li>
<li class="">10pm</li>
<li class="">11pm</li>
</ol>
JS :
$('#hour-select-mon li, #hour-select-tue li, #hour-select-wed li, #hour-select-thu li, #hour-select-fri li, #hour-select-sat li, #hour-select-sun li').on('click', function() {
$(this).toggleClass('hour-selected');
});
// get selected hours in array
var monHours = var tueHours = var wedHours = var thuHours = var friHours = var satHours = var sunHours = [];
$('#hour-select-mon .hour-selected').each(function(k,v) {
monHours.push($(v).text());
});
$('#hour-select-tue .hour-selected').each(function(k,v) {
tueHours.push($(v).text());
});
$('#hour-select-wed .hour-selected').each(function(k,v) {
wedHours.push($(v).text());
});
$('#hour-select-thu .hour-selected').each(function(k,v) {
thuHours.push($(v).text());
});
$('#hour-select-fri .hour-selected').each(function(k,v) {
friHours.push($(v).text());
});
$('#hour-select-sat .hour-selected').each(function(k,v) {
satHours.push($(v).text());
});
$('#hour-select-sun .hour-selected').each(function(k,v) {
sunHours.push($(v).text());
});
Or if you want to collect all selected items at once you may use a code similar to this:
var selected = {};
$('.hour-selected').each(function(k,v) {
var day = $(v).parent().attr('id').substr(-3, 3);
selected[day] = selected[day] || [];
selected[day].push($(v).text());
});
Try this
var selectedHours = {};
$('ol > li').on('click', function() {
var li = $(this);
li.toggleClass('hour-selected');
var parentId = $(this).parent().attr("id");
selectedHours[parentId] ? selectedHours[parentId].push(li.text()) : selectedHours[parentId] = [li.text()]
});
selectedHours will have the following structure
{
"hour-select-mon" : ["4pm", "6pm"],
"hour-select-tue" : ["9am"],
...
}

Determine the .length index of the <li> item clicked [duplicate]

This question already has answers here:
Get index of clicked element using pure javascript
(10 answers)
Closed 9 years ago.
I have a set of <li> items:
<ul id="listings">
<li id="item-0">
<div class="content">hi</div>
<li>
<li id="item-1">
<div class="content">hi</div>
<li>
<li id="item-2">
<div class="content">hi</div>
<li>
</ul>
//etc
My question is: How do I determine the index number of the clicked <li> item?.
Like if I click: <li id="item-1"> I want to know it's the second <li> index.
I can easily determine the total lenght of all <li>'s by doing:
document.querySelectorAll('#listings li').length;
And I currently have the following click listener:
document.getElementById("listings").addEventListener("click", function(e) {
if(e.target && e.target.nodeName == "LI") {
console.log(e.target.id + " was clicked");
}
});
<ul id="listings">
<li id="item-0" onclick="isClicked(0)">
<div class="content">hi</div>
</li>
<li id="item-1" onclick="isClicked(1)">
<div class="content">hi</div>
</li>
<li id="item-2" onclick="isClicked(2)">
<div class="content">hi</div>
</li>
//...
I would add an onclick function to the li. Using javascript you can collect the data.
function isClicked(number){
alert("Clicked element: "+ number);
}
var ulLength = document.getElementById('listings');
var elements = [].slice.call(ulLength.childNodes);
//[].slice.call() is used to convert array-like objects/collections into an array
function getSiblings() {
var _s = [];
elements.forEach(function (i, d) {
if (i.nodeType === 1) //prevents text nodes to be counted as siblings
_s.push(i);
});
return _s;
}
function getElmIndex(elm) {
var _siblings = getSiblings();
for (var i = 0; i < _siblings.length; i++) {
if (!(_siblings[i] && _siblings[i] !== elm)) {
return i;
}
}
}
elements.forEach(function (elm, d) {
elm.addEventListener("click", function (e) {
var _index = getElmIndex(this);
alert("Index: " + _index);
});
});
Fiddle Link
If using Jquery is not a problem, I suggest the use of the index() method: http://jsfiddle.net/JLkPs/ .
Source: http://api.jquery.com/index/

Categories

Resources