HTML / JS - li extra data field - javascript

I am currently trying to create a hidden field in a current list (li) in which I can pass another field other than just the text value.
Here is what I have so far:
HTML:
<ul id = "playlist" class="mejs-list" style="background: #00BFFF;list-style: none; padding: 0;list-style-type: none;width: 300px; height: 300px;overflow: auto" >
<li data-leaves="47" class="current">Test</li>
<li data-leaves="47">Test2</li>
</ul>
Javascript (I simplified the code):
$(".mejs-list li").click(function() {
var audio_src = $(this).text();
alert(audio_src)
var test = $(this).dataset.leaves
alert(test )
});
I get a display for "audio_src" no problem since this is simply the "text" of the item however I can not get the custom field to pass through.
Any ideas?

jQuery objects have no dataset proprty. Don't "cast" this to a jQuery Object:
$(".mejs-list li").click(function () {
var audio_src = $(this).text();
alert(audio_src);
var test = this.dataset.leaves;
alert(test);
});
Demo
Also learn how to use console.log for debugging. You can get alot more info that way, you can log and inspect objects to the console.

I think you should use $(this).attr("dataset-leaves") instead of $(this).dataset.leaves.
BTW, it is best practise to end each statement with a semi-comma.
Correction: should be $(this).attr("data-leaves")

use jQuery data() to return the value of data-leaves.
$('.mejs-list li').click(function() {
var audio_src = $(this).text(),
test = $(this).data('leaves');
alert('audio source: '+ audio_src + '\n data-laves: '+ test);
});
Demo: http://jsfiddle.net/pWuh9/

Related

How to select a specific <span> with the same class names?

I am attempting to extract some data from this block of HTML.
<div class="group-capitalization-content field-group-html-element">
<h2><span>Capitalization</span></h2>
<div class="item">
<div class="label-inline">Issued & Outstanding: </div>
<span class="number">242906121</span>
</div >
<div class="item">
<div class="label-inline">Reserved for Issuance: </div>
<span class="number">51423534</span >
</div>
</div>
I'm using an npm module called cheerio to scrape data from HTML. Thus I have the following code to try and get the "numbers".
var data = $('.group-capitalization-content .item .number').text();
Running this code results in: 24290612151423534, which is both results appended together.
How do I select the individual numbers here / separate them?
If the above example is all you need, use .eq().
First items's text() is
$('.group-capitalization-content .item .number').eq(0).text();
...and second is
$('.group-capitalization-content .item .number').eq(1).text();
If you have a more complex case and you need to store the data in an array, for later, I'd use $.map() (#Sushanth's answer) - probably a bit more specific, to rule out the possibility of other .numbers in the page:
let data = $.map(
$('.group-capitalization-content .item .number'),
function(e){ return $(e).text() }
);
You could you map method and target the .number class, which will spit out the contents into an array.
let data = $.map($('.number'), function(elem) {
return $(elem).text();
});
console.log(data);
If you don't know ahead of time how many there will be you can loop through them with an .each
$('.group-capitalization-content .item .number').each(function() {
$(this).text(); // Save this to a var or do something with it
});
How about each function to go through each of your results, like:
$('.group-capitalization-content .item .number').each(function(index, element) {
//your individual item code goes here
console.log( index + ": " + $( this ).text() );
});
i usually get all the dom elements and then loop over them to do my necessary functions. here is a working fiddle. https://jsfiddle.net/bbmtk7tm/
var data = $('.group-capitalization-content .item .number');
for(var i=0; i<data.length;i++)
{
console.log(data[i].innerHTML);
}

jQuery.each() class example Appending Div Text to Li

$EACH DEMO
anyhow iam getting the text of "div class": and printing in console.,
and iam trying to append the same text in "li > button", which is not happening, not sure where iam going wrong,
html :
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
JS:
//step - 1
$.each($('.productDescription'), function() {
var classTxt = $(this).text();
console.log(classTxt);
});
//outputs: Red Orange Green
//step - 2 now im trying to append the text to li
var liBtn = $(this).find('li').next('button');
console.log("Text of Button - "+ classTxt);
console.log(liBtn)
for (var i = liBtn.length; i >= 0; i++) {
liBtn[i]
};
Appreciate Your Help, Thanks
There are several errors in your code. classTxt is undefined outside of the each handler's context and the second this refers to window object and not to the .productDescription elements.
I'd suggest using the .append() method's callback function:
// cache the collection for better performance
var $p = $('.productDescription');
$('li button').append(function (index) {
return $p.eq(index).text();
});
http://jsfiddle.net/46yo7etz/
You could also use the .text() method:
$('li button').text(function(index, currentTextContent) {
// using indices for selecting
// the corresponding `.productDescription` element
return currentTextContent + $p.eq(index).text();
});
Please note that your fiddle's markup is invalid. li element should be child of an ul/ol element.
$('li > button').text(function() {
return $('.productDescription').eq( $('li > button').index( this ) ).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
$("button").each(function(i){
$(this).text( $(".productDescription").eq(i).text() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<ul>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
</ul>
http://jsfiddle.net/simply_simpy/uqmpvb7e/

How to keep the selected menu active using jquery, when the user comes back to page?

I have a typical menu structure -
<Ul class="nav">
<li>Menu1</li>
<li>menu2</li>
-------
</ul>
When I click on certain menu, as per my jquery written on load of layout.html, it selects particular menu.
<script>
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(this.href.trim() == window.location)
$(this).addClass("selected");
});
</script>
But on that page if I click on certain link which takes me on some other page and then when I come back the menu item does not remain selected.
How can I modify my jquery to achieve this?
Thanks in advance !
As SJ-B is saying, HTML5 Web Storage is a good solution.
If you don't intend to click more than one or two pages away from the page with your list menu, you could add a query to the link that takes you away form the page e.g. the id of one of your list menus.
href="somepage.html could become something like this href="somepage.html?menu_id=menu5
When using window.history.back(), you could then fish the id out of the URL using window.location.search and use id to select the list menu.
You can use simple css code. Use active attribute like
a:active
{
//Some style
}
You can use below code to achieve this.
var lastele=siteurl.substring(siteurl.lastIndexOf("/")+1);
jQuery(".nav>li> a").each(function(){
var anchorhref=jQuery(this).attr("href");
var finalhref=anchorhref.substring(anchorhref.lastIndexOf("/")+1);
if(finalhref==lastele){
jQuery(this).addClass("selected");
}
});
I would do something like this :
<ul class="nav">
<li id="home">Home</li>
<li id="contact">Contact</li>
</ul>
Javascript :
// http://mywebsite.com#home
// location.hash === '#home'
jQuery('.nav ' + location.hash).addClass('selected');
Try to use Session Object of HTML5.
sessionStorage.varName = id of selected item.
on load just check if the sessionStorage.varName has value or undefined, if not then get the value
`var value = sessionStorage.varName;` and set it.
Well there could be many ways, on which is this which i like and always use:
It works when you path name is same as your link name For e.g. yourwebsite.com/Menu1
function setNavigation() {
var n = window.location.pathname,t;
n = n.replace("/", "");
t = $("ul li:contains(" + n + ")");
t.addClass("active");
}
You can than define styling in your active class as you like.
I stumbled upon this when googling for something similar. I have a JQueryUI accordion menu. My menu is in an included script (classic asp), so it is on every page but I think it is a similar situation. I cobbled something together based on SJ-B's answer (don't know why it was down voted).
I have this:
function saveSession(id) {
if (window.sessionStorage) {
sessionStorage.activeMenu = $("#jqmenu").accordion("option", "active") ;
sessionStorage.activeLink = id ;
}
}
and this
$(function() {
//give every li in the menu a unique id
$('#jqmenu a').attr('id', function(i) {
return 'link'+(i+1);
});
var activeMenu = 0;
var activeLink = "";
if (window.sessionStorage) {
activeMenu = parseInt(sessionStorage.activeMenu);
activeLink = sessionStorage.activeLink;
}
$("#" + activeLink).parent().addClass("selectedmenu");
$("#jqmenu").accordion({collapsible: true, active: activeMenu, heightStyle: "content", header: "h3"});
$("#jqmenu a").click(function() { saveSession($(this).attr('id')); });
});
OK, a bit untidy and cobbled together from various suggestions (I'm still learning), but it seems to work. Tried on IE11 and Firefox. Chrome can't find localhost but that's another story.
add lines below
<script>
$(function(){
$("a[href='"+window.location+"']").addClass("selected");
});
</script>
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('.nav li').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});

Display jQuery custom attribute in alert

I'm trying to display the jQuery custom attribute in alert or console.
I tried using console.log() to log my custom data attribute but its not displaying the value.
I'm trying to display this value data-something, here's my code:
When I tried to display the value in alert it shows undefined; how to fix it?
// create a UL element
var ul = $('<ul></ul>');
// add some LI elements
ul.append(
$('<li class="bear" data-type="panda">panda bear</li>'),
$('<li class="bear" data-type="koala">koala bear</li>'),
$('<li class="wallaby" data-type="kangaroo">kangaroo</li>')
);
// this won't work because our UL is not in the dom yet
console.log($('.bear').length); //=> 0
// let's just pick the bears in our UL using our UL as the context
var bears = $('.bear', ul);
console.log(bears); //=> [li.bear, li.bear]
// lets loop through and see data attributes
bears.each(function() {
console.log($(this).attr('data-type'));
});
//=> "panda"
//=> "koala"
I have changed few of the code !
<div id="statusHtml">
</div>
<script>
// it will help to get statusHtml div tag using jquery.
var statusHtmlArr=$("#statusHtml");
$.each($('.loc-li'),funciton(){
alert("print the value in alert" + $(this).attr('data-test'));
});
/*OR*/
alert("print the value in alert" + $('.loc-li').attr('data-test'));
</script>
to show the attribute in jquery you have to use "attr()" function
Check Fiffle

Is there a way to use javascript/jquery to search a group of li tags and narrow the search down

I have been looking all over the web for ideas on how to do this. I have a DrillDown menu that at some points goes six levels deep (not my choice this is what the customer wants) I have created an xml document that holds all of these items there are a total of 106 different options that a user can select just in the side menu alone (again its what the customer wants). I want to create a search box that would allow me to type in the name of one of the selections and the list would shrink to only show the options with the word(s) that the user inputs.
My question Is there a plugin that would allow this behavior?
If not How do you search a group of li elements for text?
To code it yourself would be fairly straightforward, the jQuery below takes a string from the input #inputString and will iterate through the list items "ul li" and show/hide depending if they match the input string.
You can modify the "ul li" selector to contain other lists if needed
jQuery("#inputString").keyup(function () {
var filter = jQuery(this).val();
jQuery("ul li").each(function () {
if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
jQuery(this).hide();
} else {
jQuery(this).show()
}
});
});
I expect there are many plugins that do the same thing, give it a google!
You can try to filter by contains selector:
var matches = $( 'ul#myMenu' ).find( 'li:contains(search string) ' );
$( 'li', 'ul#myMenu' ).not( matches ).slideUp();
matches.slideDown();
See example on jsFiddle
How do you search a group of li elements for text?
var filteredLIS = $("li:contains('" + yourQuery + "')");
Reference: http://api.jquery.com/contains-selector/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Start here: Search Service area via jQuery
window.filter = function(element)
{
var value = $(element).val().toUpperCase();
$(".left_message > li").each(function()
{
if ($(this).text().toUpperCase().search(value) > -1){
$(this).show();
}
else {
$(this).hide();
}
});
}
});
</script>
<input type="text" placeholder="Enter text to search" onkeyup="filter(this);">
<ul role="tablist" class="left_message">
<li><span>Anupk Kumar</span></li>
<li><span>Pradeep Kumar</span></li>
<li><span>Zahid Gani</span></li>
<li><span>Amitabh</span></li>
<li><span>Chandan Gupta</span></li>
</ul>
Result : Search Zahid , they return following output
<ul role="tablist" class="left_message">`enter code here`
<li><span>Zahid Gani</span></li>
</ul>
Using the drilldown sample here:
http://www.designchemical.com/lab/jquery-drill-down-menu-plugin/getting-started/
This is my suggestion:
$('#drilldown').find("a:contains('Product')");
You can try using this concept:
$('.search').keyup(function(){
if( $(this).val().length > 0 ){
var foundin = $('#drilldown').find('li a:contains("'+$(this).val()+'")');
}
});

Categories

Resources