jQuery $(this).data() returns undefined [duplicate] - javascript

This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
Closed 3 years ago.
I'm trying to fix the following code:
const $configuratorMenus = $('.configurators-menu ul li');
$configuratorMenus.click(() => {
let panelID = $(this).data("id");
let panelID2 = $(this).attr("data-id");
console.log(panelID, panelID2);
//$(`#${panelID}`).slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
<ul>
<li data-id="shapes">
<a href="#">
Shape
</a>
</li>
</ul>
</div>
It keeps consoling undefined, what am I doing wrong? I couldn't relate any other solution.
Note: I would like to solve this by using the arrow function.

Since you are using arrow function , this will refer window object in this case. You can use e.target.Where e is event object. Also the data attribute is on li but the event is originating from a. So change $configuratorMenus to $('.configurators-menu ul li a')
const $configuratorMenus = $('.configurators-menu ul li a');
$configuratorMenus.click((e) => {
// get the parent element from the target
let panelID = $(e.target).parent().data('id');
console.log(panelID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
<ul>
<li data-id="shapes">
<a href="#">
Shape
</a>
</li>
</ul>
</div>

This one should resolve your problem -
const configuratorMenus = $('.configurators-menu ul li a');
configuratorMenus.click(function () {
let panelID = $(this).parent().data("id");
console.log(panelID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
<ul>
<li data-id="shapes">
<a href="#">
Shape
</a>
</li>
</ul>
</div>

Related

Loop through ol in jQuery and remove class and text

I have to loop through a ol and then get each of the li and then remove the text and add "<a" element to it.
Following is the html that is rendered:
<ol class="progress">
<li class="list-group-item text-muted list-group-item-success active">
General Information<span>1</span>
</li>
</ol>
I want to remove all the classes except "active" and then wrap the text with General Information
Like below
<ol class="progress">
<li class="active">
General Information<span> 1</span>
</li>
</ol>
I have tried to loop through the Ol using the script below but it seems to not find anything
$('ol.progress').each(function (i, li) {
var listItem = li;
var lm = $(li).text();
console.log(lm);
});
I see you are using JQuery - so let's stick to this.
You are looping over the ol but you want to loop over the ol's lis.
So replace
$('ol.progress').each....
by
$('ol.progress li').each....
You can remove all classes with the .removeClass() without any parameters.
But as you want to preserve the active-class you have to preserve this attribute - in my version of the code (see below) I will use a variable for this.
In addition you want to replace the HTML-part and not the text-part - so your snippet would read
$('ol.progress li').each(function () {
var is_active = false;
is_active = $(this).hasClass('active');
$(this).removeClass();
if(is_active){
$(this).addClass('active');
}
var newcontent = '' + $(this).html() + "";
$(this).html(newcontent);
});
With vanilla js:
document
.querySelectorAll('ol.progress > *') // all children of <ol> with class .progress
.foreach(elem => {
elem.className = 'active'
elem.innerHTML = `${elem.innerHTML}`
})
With jquery, as you can see, I check if the element has a class, then I remove all the classes and add active if it had it.
$('ol.progress li').each(function(i, li) {
var listItem = li;
if ($(li).hasClass('active')) {
$(li).removeAttr('class');
$(li).addClass('active');
} else {
$(li).removeAttr('class');
}
});
.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol class="progress">
<li class="list-group-item text-muted list-group-item-success active">
General Information<span>1</span>
</li>
<li class="list-group-item text-muted list-group-item-success">
General Information<span>2</span>
</li>
<li class="list-group-item text-muted list-group-item-success">
General Information<span>3</span>
</li>
</ol>
In your code you forgot li into selector so $('ol.progress li') instead of $('ol.progress')

how do i use querySelector the right way [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I want the navbar <ul> to disappear when I click it. With querySelectorAll() I selected all <li>s in the navbar. Then I added a click event listener to it. So when I click it, it should toggle the class of the navbar <ul> to "active" and then disappear.
It works with the toggle button but not with the <li>s.
<i id="togglebtn" class="fas fa-bars"></i>
<nav class="navbar">
<div class="brand-title">brandName</div>
<div class="navbar-links">
<ul id="ul">
<li class="jsscrolltrigger">Start</li>
<li class="jsscrolltrigger">Galerie</li>
<li class="jsscrolltrigger">Anfahrt</li>
<li class="jsscrolltrigger"><a href="#Speisekarte">Speisekarte</>
</li>
</ul>
</div>
</nav>
<script type="text/javascript">
var togglebtn = document.getElementById("togglebtn");
togglebtn.addEventListener("click", function () {
ul.classList.toggle("active");
});
// this following part doesnt work //
// i want the ul(navbar) to disappear when i click it //
var a = document.querySelectorAll(".jsscrolltrigger");
var ul = document.getElementById("ul");
a.addEventListener("click", function () {
ul.classList.toggle("active");
});
</script>
querySelectorAll returns a NodeList. You have to iterate the list and add the event listener to every node.
For example:
var togglebtn = document.getElementById("togglebtn");
togglebtn.addEventListener("click", function() {
ul.classList.toggle("active");
});
var nodeList = document.querySelectorAll(".jsscrolltrigger");
var ul = document.getElementById("ul");
nodeList.forEach(node => {
node.addEventListener("click", function() {
ul.classList.toggle("active");
});
})
<i id="togglebtn" class="fas fa-bars"></i>
<nav class="navbar">
<div class="brand-title">brandName</div>
<div class="navbar-links">
<ul id="ul">
<li class="jsscrolltrigger">Start</li>
<li class="jsscrolltrigger">Galerie</li>
<li class="jsscrolltrigger">Anfahrt</li>
<li class="jsscrolltrigger">Speisekarte</li>
</ul>
</div>
</nav>
When you use Document.querySelectorAll() It doesn't return a single element. It return a NodeList on which you can call forEach to loop through all of the item.
let a = document.querySelectorAll('.jsscrolltrigger');
let ul = document.getElementById("ul");
a.forEach(function(element) {
element.addEventListener('click', function(e){
e.preventDefault();
ul.classList.toggle("active");
});
});
.active {
border: 2px solid red;
}
<nav class="navbar">
<div class="brand-title">brandName</div>
<div class="navbar-links">
<ul id="ul">
<li class="jsscrolltrigger">Start</li>
<li class="jsscrolltrigger">Galerie</li>
<li class="jsscrolltrigger">Anfahrt</li>
<li class="jsscrolltrigger"><a href="#Speisekarte">Speisekarte</>
</li>
</ul>
</div>
</nav>
If you don't want to use forEach to perform the loop you can force the NodeList to be consider as an Array by passing it to the Array.from() method which allows you to perform any array operation on selected elements
Array.from(a).map(function(){ /*...*/ });
Array.from(a).filter(function(){ /*...*/ });

JQuery addClass method not working on $(this) element or event.currentTraget [duplicate]

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 1 year ago.
I am trying to update the active state of a navigation tab. When the tab is clicked (newActive) is suppose to gain the class .active and the previous active tab (oldActive) needs to loose it.
So far I am able to remove the active class from oldActive, I also tried aadding a class to it and worked fine, but I am not able to do any changes to newActive when I defined it as $(this) nor when I define it as event.currentTarget.
I am also not getting any errors in the console so I can't get a lead on what's going on.
JQuery code:
$('.navigation_tabs li').click( event => {
let oldActive = $('.navigation_tabs li.active');
let newActive = event.currentTarget;
oldActive.removeClass("active");
// this line is not working nor giving any errors
newActive.addClass("active");
loadContent(data[newActive.dataset.list]);
});
HTML nav markup:
<div class="navigation">
<ul class="navigation_tabs">
<li class="active" data-list="build">Build</li>
<li data-list="plan">Plan</li>
<li data-list="innovate">Innovate</li>
<li data-list="interact">Interact</li>
<li data-list="scale">Scale</li>
<li data-list="service">Service</li>
<li data-list="enhance">Enhance</li>
<li data-list="general">General</li>
</ul>
</div>
There is actually a very simple example of this. why do you choose the hard one? The use of event.currentTarget applies to ES6. Not for jquery.
$('.navigation_tabs li').click(function() {
$(this).addClass('active').after(function() {
$('.active').not($(this)).removeClass('active')
});
});
.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navigation">
<ul class="navigation_tabs">
<li class="active" data-list="build">Build</li>
<li data-list="plan">Plan</li>
<li data-list="innovate">Innovate</li>
<li data-list="interact">Interact</li>
<li data-list="scale">Scale</li>
<li data-list="service">Service</li>
<li data-list="enhance">Enhance</li>
<li data-list="general">General</li>
</ul>
</div>
addClass is a JQuery function, but event.currentTarget is plain javascript event, so you can try this:
$('.navigation_tabs li').click( event => {
let oldActive = $('.navigation_tabs li.active');
let newActive = $(event.currentTarget); // change here
oldActive.removeClass("active");
// this line is now working
newActive.addClass("active");
loadContent(data[newActive.dataset.list]);
});

How to delete a specific <li> of a particular <ul> from a list of several <ul>s

I have 10-15 unordered lists in my HTML page, each containing a delete button next to each list item.
For each li to be uniquely identifiable, I have assigned to its id: its parent's id and its own category_name.
However, when I perform the remove() -- it doesn't work. The li does not get removed from its parent.
I already have an input box associated with each ul to add li's to the specific ul which is working.
<script>
function remove_category(ident){
$("#"+ident).remove;
}
function add_category(ul_id, input_id){
var ul = $("#"+ul_id);
var added_category = $("#"+input_id).val();
$(ul)
.append('<li class="list-group-item" id="'+added_category+'">'+added_category+'<button type="button" id="delete-category-btn" onclick="remove_category('+ul_id+added_category+');"><i class="fa fa-times delete-fa" aria-hidden="true"></i></button></li>')
}
</script>
The remove_category() function does not perform any action.
Probably because of the event handler is not taking dynamic element. Use .on to make the click event work on dynamic element
Here is the example.
$(document).on("click", ".added-category", function() {
var parent = $(this).closest("li");
parent.after("<li>" + parent.html() + "</li>");
});
$(document).on("click", ".remove-category", function() {
var parent = $(this).closest("li");
parent.remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
some text
<button class="added-category">Add</button>
<button class="remove-category">Remove</button>
</li>
</ul>
Try to use this,
function removeLi(dhis){
dhis.parent().remove()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li >list 1 <button onclick="removeLi($(this))">remove</button></li>
<li>list 2 <button onclick="removeLi($(this))">remove</button></li>
<li >list 3 <button onclick="removeLi($(this))">remove</button></li>
<li >list 4 <button onclick="removeLi($(this))">remove</button></li>
<li >list 5 <button onclick="removeLi($(this))">remove</button></li>
</ul>

Displaying selection text in span

So let's say I have this code:
<span id="select_list">
<ul>
<li><a id="1">1</a></li>
<li><a id="2">2</a></li>
<li><a id="3">3</a></li>
</ul>
</span>
<span id="selection"></span>
And let's also assume that there are a lot of list elements, ex. '4,5,6,7... etc'.
Can I get a html file, that is basically just text, that corresponds to the list element's ID (ex. 1.html, 2.html,... etc), to show in 'selection'?
If so how?
Thanks for your time. Hope I explained it well.
Something like this (jQuery) should work:
var list = $("#select_list");
var sel = $("#selection");
$("a", list).on("click", function(){
var id = $(this).attr("id");
sel.load(id+".html");
});
<div id="select_list">
<ul>
<li id="1">1</li>
<li id="2">2</li>
<li id="3">3</li>
</ul>
</div>
<div id="selection"></div>
i would use a div not span spans are for if you want to change the size of something particular like this:
<li id="1" href="#"><a href="#"><span style="color: red;
font-size: 30px">1</span></a></li>
and from what i am understanding you want a selector to select them in css?
if so this is how:
#select_list ul li:nth_child(1) {
}
or
#select_list ul li#2 {
}
hope this helps you
I would suggest using data-attributes instead of IDs.
HTML
<ul class='selection-list'>
<li data-name='Dog'>Dog</li>
<li data-name='cat.html'>Cat</li>
<li data-name='45'>Fourty Five</li>
<li data-name='Triangle'>Three sides</li>
</ul>
<div class="output js-output"></div>
jQuery
var $output = $('.js-output');
$('.selection-list li').on('click', function() {
var selectionValue = $(this).data('name');
$output.text(selectionValue);
});
CSS
.selection-list li {
cursor: pointer;
}
jsFiddle
iframe
I'm starting to think that you are asking for an iframe with dynamic source. The question is unclear. You may want to try and rewrite it. - Here is what I think you may be after...
HTML
<ul class='selection-list'>
<li data-url='http://reputable.agency'>Reputable Agency</li>
<li data-url='http://perpetual.education'>Perpetual Education</li>
<li data-url='http://example.com/index.html'>Example.com</li>
</ul>
<iframe src='http://example.com' class="output js-output"></iframe>
JavaScript / jQuery
var $output = $('.js-output');
$('.selection-list li').on('click', function() {
// get the 'data-url' from the element...
var selectionValue = $(this).data('url');
// put that data-url into the src attribute of the iFrame
$output.attr('src', selectionValue);
});
Also..
Note that if you are using the same domain for all of these, you can build those urls differently to keep things simple.
<li data-url='index.html'>Example.com</li>
$output.attr('src', 'http://yoursite.com/' + selectionValue);
jsFiddle
AJAX
Now I'm wondering if you mean AJAX. Here is an example - but it's not tested because I don't have access to a bunch of relative URLs - but here is the basics - and should lead you to the right documentation.
HTML
<ul class='selection-list'>
<li data-url='index.html'>Reputable Agency</li>
<li data-url='index.html'>Perpetual Education</li>
<li data-url='index.html'>Example.com</li>
</ul>
<div class="output js-output"></div>
JavaScript / jQuery
var $output = $('.js-output');
var getOtherPage = function(target) {
$.ajax({
url: target,
success:function(response){
$output.html(response);
},error:function(){
alert("error");
}
});
};
$('.selection-list li').on('click', function() {
var selectionValue = $(this).data('url');
getOtherPage(selectionValue);
});

Categories