I have a class amt and when that class is clicked I want to get the values of the clicked <h6>, <span> and <label> tags.
How do I do this in jquery? I have already seen a question here Get value of List Item with jQuery but it uses same under tag but i have to get different elemet value under same tag
<li class="amt" id="diecut_am1">
<h6>50</h6>
<span>$59.00</span>
<label>$51.30</label>
</li>
<li class="amt" id="diecut_am2">
<h6>100</h6>
<span>$68.00</span>
<label>$61.20</label>
</li>
Try this
$(".amt").click(function() {
var elem1 = $(this).find("h6").html();
var elem2 = $(this).find("span").html();
var elem3 = $(this).find("label").html();
alert(elem1);
alert(elem2);
alert(elem3);
});
https://jsfiddle.net/kLe5kLc3/1/
You could do something like this:
$( document ).ready(function() {
$('.amt').on("click", function() {
var h6 = $(this).find('h6').text();
var span = $(this).find('span').text();
var label = $(this).find('label').text();
});
});
Demo: https://jsfiddle.net/12q12k52/
here's the JS way :
var amt = document.querySelectorAll('.amt')
//add event listener to all .amt elements
var amtArr = [].slice.call(amt)
amtArr.forEach(function (x) {
x.addEventListener('click', listChilds, true)
});
//we retrive the target properties
function listChilds(e) {
console.log(e.path[1]) //all the children
//if you want one in particular it would be
console.log(e.target.childNodes[0])
}
<li class="amt" id="diecut_am1">
<h6>50</h6>
<span>$59.00</span>
<label>$51.30</label>
</li>
<li class="amt" id="diecut_am2">
<h6>100</h6>
<span>$68.00</span>
<label>$61.20</label>
</li>
You can iterate over the children of the clicked elements
$(this).children()
Related
I am trying to store some list item into a variable and then loop through the variable and display only the list items that have a certain data attribute. It is worth mentioning that just using a simple show/hide on the li's on the page will not work for what I'm doing. https://jsfiddle.net/0jbnLv0k/
HTML:
<ul>
<li data-color="blue"></li>
<li data-color="red"></li>
<li data-color="green"></li>
<li data-color="blue"></li>
<li data-color="red"></li>
<li data-color="green"></li>
</ul>
<button class="blue">blue</button>
<button class="red">red</button>
<button class="yellow">yellow</button>
Jquery:
var items = $('ul li');
items.remove();
var result = $.grep(items, function(e){ return e.data == 'blue'; });
$('ul').html('<li>' + result + '</li>');
Problem is that
typeof e.data === 'undefined'
Solution is this:
var items = $('ul li');
items.remove();
var result = $.grep(items, function(e){
return $(e).attr('data-color') == 'blue';
});
$('ul').append( result );
But this is very bad end expensive ( time consuming ) way to display DOM elements. Much better would be add class with
display: none;
property.
Instead all this code you can use only one line:
$("li:not([data-color='blue'])").addClass('hide')
$("button").click(function() {
var getClass = $(this).attr("class");
$("ul").find("li").not("li[data-color="+getClass+"]").remove();
});
you could use not selector removing all list elements except the selected class.
https://jsfiddle.net/0jbnLv0k/5/
I have
<ul id="list">
<li data-markerid="0" class="">
<div class="list-label">A</div>
<div class="list-details">
<div class="list-content">
<div class="loc-id">2</div>
<div class="loc-addr">England</div>
<div class="loc-dist">2 miles</div>
<div class="loc-addr2">Test</div>
<div class="loc-addr2">Bristol</div>
</div>
</div>
</li>
<li data-markerid="1" class="">
<div class="list-label">A</div>
<div class="list-details">
<div class="list-content">
<div class="loc-id">3</div>
<div class="loc-addr">England</div>
<div class="loc-dist">60 miles</div>
<div class="loc-addr2">Test</div>
<div class="loc-addr2">London</div>
</div>
</div>
</li>
</ul>
I'm wanting to extract the value of this using JQuery.
I tried:
var targetID = $(this).find('.loc-id').text();
But this gets me values of both loc-id's. I want just the one that I'm selecting (clicking).
For full context, please look here: Parsing data using JQuery
$('#list').click(function () {
//Change the src of img
var targetID = $(this).find('.loc-id').text(); // Get the ID
// Since array of objects isn't indexed, need to loop to find the correct one
var foundObject = null;
for (var key in parsedArray) {
if (parsedArray.hasOwnProperty(key) && parsedArray[key].id == targetID) {
foundObject = parsedArray[key];
break;
}
}
// If the object is found, extract the image and set!
if (!foundObject)
return;
var imageSrc = foundObject.LocationPhoto; // From the object
$('#location-image').attr('src', imageSrc); // Set the new source
});
Thanks
In your click handler, this references the <ul> element which has multiple <li> children.
Change the click handler to act as a delegate instead:
$('#list').on('click', 'li', function () {
Now, inside the click handler, this references an <li> element so the search should only yield a single value.
For var targetID = $(this).find('.loc-id').text(); to work, you must be clicking an element that is an ascendant of only one .loc-id. For example:
$('.list-details').on('click',function(){
var targetID = $(this).find('.loc-id').text();
});
You need to change selector. In your event handler. $(this) referes to ul which has multiple loc-id thus when you are using text() its concatenating text.
Use
$('#list li').click(function () {
//Change the src of img
var targetID = $(this).find('.loc-id').text(); // Get the ID
alert('targetID: ' + targetID)
});
instead of
// When we select the item
$('#list').click(function () {
//Change the src of img
var targetID = $(this).find('.loc-id').text(); // Get the ID
DEMO
You could use event.target in case you are delegating on #list:
Demo: http://jsfiddle.net/abhitalks/CxcU8/
$("#list").on("click", function(e) {
var $t = $(e.target);
if ($t.hasClass('loc-id')) {
alert($t.text());
}
});
I'm trying to display the full list that have the same id that matches with the select option. But I can't figure out how to get the id from the attribute by using the name to be able to filter it.
The html example:
<select id='groopy' onchange='see();'>
<option>default</option>
<option>lista1</option>
<option>list1</option>
</select>
<ul id='grupo'>
<li id='list1' name="lista">Playground (Rangbhoomi)</li>
<li id='default' name="lista">Empire Made Me</li>
<li id='default' name="lista">Transmission</li>
<li id='lista1' name="lista">Hostel Room 131</li>
<li id='default' name="lista">A Disobedient Girl</li>
<li id='default' name="lista">Travels in the Land of Kubilai Khan</li>
<li id='list1' name="lista">The Indian Mutiny</li>
<li id='lista1' name="lista">Beauty and Sadness</li>
<li id='default' name="lista">The Collaborator</li>
<li id='list1' name="lista">I, Lalla</li>
<li id='default' name="lista">No Full Stops in India</li>
<li id='lista1' name="lista">For Lust of Knowing</li>
<li id='default' name="lista">On the Road to Kandahar</li>
</ul>
And the script I'm trying:
<script>
function see(){
var listita = document.getElementById('groopy').options[document.getElementById('groopy').selectedIndex].value;
var items = document.getElementsByName("lista");
var items_id = document.getElementsByName("lista").getAttribute('id');
if(listita==items_id){
for(var i = 0; i < items.length; i++)
{
document.getElementById("description").innerHTML = items[i].outerHTML;
}
}
}
onload= see();
</script>
By the way, the select and the ul are generated dynamically so I don't actually now the id's that could be provided. I'm trying a little different approach here .
When I manage to make the select filter work, the for stop working. WHY? I'm going crazy with this. Please help!!
Firstly you are having multiple elements with same id's which is wrong.. Cause getElementbyId will only fetch the first element encountered by it.
Replace then with class instead
Next you are overwriting the HTML for every iteration, so you will always have the last item appended to it.
Instead store that in a variable and append it after the for loop.
you need to bind your element with a change event, otherwise your call only works once when the page loads for the first time.
Try this
// Cache the selector as you are using it multiple times
var dropdown = document.getElementById('groopy');
function see() {
// set the selected option
var listita = dropdown.options[dropdown.selectedIndex].value
items = document.getElementsByClassName(listita);
html = '';
// For each item with class name, iterate over it and store in a string
for (var i = 0; i < items.length; i++) {
if (items[i].className == listita) {
console.log((items[i].outerHTML));
html += items[i].outerHTML
}
}
// set the html after the for loop
document.getElementById("description").innerHTML = html;
}
onload = see();
// attach the change event handler
dropdown.addEventListener('change', see);
Check Fiddle
try changing the id's to class in the li tags and use this function...
function see(){
var selectedVal = document.getElementById('groopy').options[document.getElementById('groopy').selectedIndex]. value;
var items = document.getElementsByClassName(selectedVal);
var html = '';
for(var i = 0; i < elements.length; i++)
{
html += items[i].outerHTML;
}
document.getElementById("description").innerHTML = html;
}
onload= see();
Step1 - Change id to class
Step2 - Traverse DOM elements with jQuery class selector. In this way replace document.getElementId('id) with $('.className')
I have menu list that contains:
<ul class="content_menu tabs">
<li class="pager_link_0_active"></li>
<li class="pager_link_1"></li>
<li class="pager_link_2"></li>
<li class="pager_link_3"></li>
<li class="pager_link_4"></li>
<li class="pager_link_5"></li>
<li class="pager_link_6"></li>
<li class="pager_link_7"></li>
<li class="pager_link_8"></li>
</ul>
What I want to do is when particular link is clicked I need to remove active from li class name that contains active (e.g pager_link_0_active) and add active to the li that is clicked (e.g pager_link_2_active)
I know there is one way to make it:
$(".active").removeClass("active");
$(this).addClass("active");
but in my situation, active is not seperated, it is part of class name.
According to standards ul can contain only element but what you want can be achived these way:
$(function () {
$('ul.content_menu.tabs a.tab').click(function () {
var newActive = $(this);
if (newActive.hasClass('active')) {
return;
}
var oldActive = $('ul.content_menu.tabs a.tab.active');
oldActive.removeClass('active');
var oldIndex = $('ul.content_menu.tabs a.tab').index(oldActive);
oldActive.children().attr('class', 'pager_link_' + oldIndex);
var newIndex = $('ul.content_menu.tabs a.tab').index(newActive);
newActive.addClass('active');
newActive.children().attr('class', 'pager_link_' + newIndex + '_active');
});
});
Here is fiddle
It would be better to make it a separate class <li class="pager_link_1 pager_active">, then you can remove and add pager_active easily.
If the LI will always have just one class, try this:
var active_li = $(".active li");
var active_class = active_li.attr("class");
active_li.attr("class", active_attr.replace("_active", "");
var this_li = $(this).children("li");
var this_class = this_li.attr("class");
this_li.attr("class", this_class+"_active");
I need to use prototype JavaScript library on a project and wanted to add tabbed box to HTML.
The click handler has a simple task - set selected on parent <li> element and show linked DIV id element (rel tag on <li> has element id name)
<div class="tabInterface">
<ul class="tabSelector">
<li class="selected" rel="searchLast">Popularna iskanja</li>
<li rel="searchMine">Moje zadnje iskanje</li>
</ul>
<div class="tabContent selected" id="searchMine">
box 1 content
</div>
<div class="tabContent" id="searchLast">
box 2 content
</div>
</div>
Final result after 1 hour of hard labour.
initTabInterface = function() {
//requires prototype
var tabClick = function(event){
Event.stop(event);
var $el = Event.element(event);
var $menu = $el.up('.tabSelector');
var liList = $menu.descendants().filter(function(el){return el.match('li')});
liList.invoke('removeClassName', 'selected');
$el.up().addClassName('selected');
var rel = $el.up().readAttribute('rel');
var $interface = $menu.up('.tabInterface');
var tabList = $interface.descendants().filter(function(el){return el.match('.tabContent')});
tabList.invoke('removeClassName', 'selected');
$interface.down('#'+rel).addClassName('selected');
};
$$('.tabInterface .tabSelector li a').each(function(el){
var $el = $(el);
Event.observe($el, 'click', tabClick);
});
};
Event.observe(window,"load", function(){
initTabInterface();
});
Is there an easier way of traversing in prototype than with the bunch of up, down, filter, match, invoke and each?
This is pretty much you can get:
initTabInterface = function() {
//requires prototype
var tabClick = function(event){
Event.stop(event);
var $el = Event.element(event);
var rel = $el.up().readAttribute('rel');
// remove old selected classes
$el.up('.tabInterface').select('.selected')
.invoke('removeClassName', 'selected');
// add new selected classes
[ $(rel), $el.up() ].invoke('addClassName', 'selected');
};
$$('.tabSelector li a').each(function(el){
Event.observe($(el), 'click', tabClick);
});
};
Event.observe(window,"load", function(){
initTabInterface();
});
I do not know Prototype well enough to quickly refactor your code, but you can use Element.siblings instead of going up and then descending down. Alternatively, you can just enumerate by class names (doesn't work well if you have more than one tab control).
$el.siblings().invoke('removeClassName', 'selected');
Also
$interface.down('#'+rel).addClassName('selected');
is unnecessary because you can only have one element with an id in the whole document. Can change it to:
$(rel).addClassName('selected');