Data attribute is returning undefined - javascript

I am using jQuery to set a data attribute filtername on an onClick which works fine.
$('#tag-group ul').append('<li><i class="fa fa-times" aria-hidden="true" data-filtergroup="'+filterGroup+'" data-filtername="'+filterName+'"></i>'+text+'</li>');
It renders out on the screen ok as
<li><i class="fa fa-times" aria-hidden="true" data-filtergroup="location" data-filtername="Melbourne"></i> Melbourne</li>
I am then trying to pick it up again on another onClick but it comes back as undefined. When I console log $(this).text(); it works but when I console log $(this).data('filtername'); it is undefined. Is the dom hiding it if it is generated by jQuery?
$(document).on('click','#sau-filter-tags ul li', function(event){
var text = $(this).text();
var filterName = $(this).data('filtername');
console.log(filterName); //Undefined
});

filtername is attribute of i tag in li.
You need to select i tag :
$(document).on('click', '#sau-filter-tags ul li i', function(event) {
var text = $(this).text();
var filterName = $(this).data('filtername');
console.log(filterName); //Undefined
});
or you need to attach event to li and find I in this , Example:
$(this).find('i').data('filtername')

You are targeting a data attribute on i tag. So you have to create an event upon i
$(document).on('click','#sau-filter-tags ul li i', function(event){
var text = $(this).text();
var filterName = $(this).data('filtername');
console.log(filterName); //Undefined
});

You are accessing the attribute on your containing <li> rather than the <i> inside. Try the following:
$('#sau-filter-tags li').on('click', function () {
var i = $(this.firstElementChild)
var text = i.text()
var filterName = i.data('filtername')
console.log(filterName) //=> 'Melbourne'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li><i class="fa fa-times" aria-hidden="true" data-filtergroup="location" data-filtername="Melbourne"></i> Melbourne</li>

Related

How to apply AddEventListener to created element?

I need your help I working on an application and I'm a beginner in JS
I want to apply addEventListener on a created element
const i = document.querySelector(".fas");
li.innerHTML = `<i class="fas fa-times"></i>`;
i.addEventListener("click", removeTask);
function removeTask(e) {
e.preventDefault();
li.style.textDecoration = "line-through";
}
It's not working can anybody help me, please.
Thanks in advance
You used li when you should have used i. I'm not sure if your variable li is defined somewhere else, but that might be causing the problem. Otherwise, everything looks fine.
Try using this:
const fas = document.getElementByClassName("fas");
li.innerHTML = `<i class="fas fa-times"></i>`;
i.addEventListener("click", function(){ removeTask(e));
function removeTask(e) {
e.preventDefault();
li.style.textDecoration = "line-through";
}
I think you want to click on the times icon and apply line through to your li element.
In your case as in mine, i element as an innerHTML of another element this means it exists !
Here is a simple example below
document.querySelector("div").innerHTML = "<i class='fas fa-times'></i>"
document.querySelector("i").addEventListener("click", ()=>{
console.log("Hello Stackoverflow")
//your code here for callback
})
i{
cursor: pointer;
}
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<div>
Hello world
</div>

How do I change the last textual node child in JavaScript

My Solution (EDIT : 2015-12-08) :
// FIRST WE GET THE PARENT ELEMENT
var parentEstim = document.getElementById("onglet_estim");
// MAKE A TABLE OF HIS CHILD
var enfantsEstim = parentEstim.childNodes;
// KNOW HOW MANY CHILDREN THE PARENT ELEMENT HAVE WITH .length
var Nbenfants = enfantsEstim.length;
....
for (var i = 0; i <= Nbenfants; i++) {
// IF THE CHILD ELEMENT [i] IS A HTML ELEMENT
if (enfantsEstim[i].nodeType === 1) {
enfantsEstim[i].lastChild.data = ''; // REMOVE LAST TEXT NODE
enfantsEstim[i].classList.remove('isActive');
}
document.getElementById('onglet_estim').style.width = '220px';
ClickedElement.className = 'isActive';
// ADD NEW VALUE IN THE LAST TEXT NODE FOR THE CLICKED ELEMENT
ClickedElement.lastChild.data = ' Gares';
}
DEMO : http://codepen.io/Zedash/details/pjMEMY
The Problem :
I have a little problem, I want to change the last textual node child value of a link <a> element.
For exemple, for the first link, we see the word "Saisie" wrote in it and I want to remove the text in this element if the user click on an other link and add a right text for the clicked element.
function changeInputAdresse(ClassName) {
if (ClassName.className !== 'isActive') {
ClassName.className = 'isActive';
switch(ClassName.id) {
case 'linkGares' :
ClassName.insertAdjacentHTML('beforeEnd',' Gares');
ClassName.previousElementSibling.classList.remove('isActive');
ClassName.nextElementSibling.classList.remove('isActive');
ClassName.previousElementSibling.insertAdjacentHTML('beforeEnd','');
ClassName.nextElementSibling.insertAdjacentHTML('beforeEnd','');
break;
}
}
};
// THE CODE IS NOT FINISHED OF COURSE !
a {
text-decoration:none;
color:#000;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<a id="linkSaisie" class="isActive" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-map-marker"></i> Adresse</a>
<a id="linkGares" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-train"></i></a>
<a id="linkAeroports" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-plane"></i></a>
<a id="linkLoisirs" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-fort-awesome"></i></a>
<!--THE PART OF CODE WHERE I HAVE SOME PROBLEMS-->
Thanks for your ansewers ! :)
I don't quite get what you exactly would like, but to target and change the element after an italic I would use this jQuery and vanilla JS combination:
$("#myLink").find(">i").get(0).nextSibling.nodeValue = "Changed text";
DEMO: http://jsfiddle.net/u9jq2bvy/
IIRC there is no jQuery method to target a text node, so you need some native JS.
Please let me know if I misunderstood the question and I'm gonna delete my answer.
UPDATE
Based on the comment here is a possible solution.
$(document).on("click", ".myLink", function() {
// clear all texts
$(this).parent().find("a>span").text("");
$(this).addClass("active");
$(this).children("span").text("Active text");
});
DEMO http://jsfiddle.net/u9jq2bvy/1
And here is a modified version which simply shows/hides the spans.
DEMO http://jsfiddle.net/u9jq2bvy/3/
You can use jQuery siblings
changeInputAdresse(element){
element = $(element)
if(!element.hasClass('isActive')){
element.addClass('isActive');
element.siblings().removeClass('isActive');
element.text(element.attr('id').replace('link','')) //if that's the way you get value
element.siblings().text('')
}
}

Jquery Remove Element from List

I have a list in JQuery that's called additionalInfo, which is filled in using this JQuery function:
$('#append').on('click', function () {
//check if the following area is valid before moving on, check the jquery validation library
var text = $('#new-email').val();
var li = '<li>' + text + 'input type="hidden" name="additionalInfo" value="'+text+'"/> </li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
The point of the function is not only to store the info in a list that can be used later, but also to render a <li> with the info text in it. Right now I have another button on each <li> that when pressed, makes the li vanish, but I also need to add code to it that completely removes the info text from the additionalInfo list. This is the code I have for that method so far:
$('#removeEmail').on('click', 'li>.remove-btn', function (event){
$(event.currentTarget).closest('li').remove();
});
How can I get the segment of info text out of the li and then remove it from additionalInfo?
You have few problems. First of all when you create the new items, your markup is not correct. You were missing the opening bracket of input tag. Also i changed the code for delete so that it listens for the click event on any item with class remove-btn under the li element. This should delete the item when you click the remove link inside the li.
$(function(){
$('#append').on('click', function () {
var text = $('#new-email').val();
var li = '<li>' + text + '<input type="hidden" name="additionalInfo"
value="'+text+'"/>
<a href="#" class="remove-btn" >remove</a></li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
$(document).on('click', 'li>.remove-btn', function (event){
var _this =$(this);
_this.closest('li').remove();
});
});
Here is a working jsfiddle

Get Values of sub elements of clicked class using jquery

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()

Using jQuery to load icon based on <label> contents

I have a website where the content is dynamically loaded from a database. The contents varies for each label.
One may be generated as General:, whilst another may be generated as TV:.
My question is, is there any way that jQuery could (based on the HTML output for the label) replace the NAME: with a font awesome icon?
So for example:
<label>TV:</label>
Would become:
<i class="fa fa-film fa-2x"></i>
Try
var icons = {
'tv:': 'film',
'edit:': 'edit'
};
$('label').replaceWith(function () {
var text = $(this).text().trim().toLowerCase(),
icon = icons[text];
return icon ? '<i class="fa fa-' + icon + ' fa-2x"></i>' : undefined;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css">
<label>TV:</label>
<label>TsV:</label>
<label>EDIT:</label>
You could use the :contains selector http://api.jquery.com/contains-selector/
$("label:contains('TV')").html('<i class="fa fa-film fa-2x"></i>');
$("label:contains('TV')").html('<i class="YOUR CLASS"></i>');
or if you could add class or id in that label you could change it easily like
$("#ID").html('<i class="YOUR CLASS"></i>');
$(".CLASS").html('<i class="YOUR CLASS"></i>');
You can replace them with JQuery for example
var icons = {
"TV:" : "film"
};
var $labels = $('label');
$labels.each(function(index){
var icon = icons[$(this).text()];
$(this).replaceWith($("<i>").addClass('fa').addClass('fa-' + icon).addClass('fa-2x'));
});
And see Fiddle: http://jsfiddle.net/m19hjnoa/
You could take different aproaches on that.
My personal favorite would be to just send the right label from the server.
otherwise you could run this jQuery Script: http://jsfiddle.net/ehdgL6so/
// try to select as less elements as possible for speed
// for example if they are in a div with class foo try jQuery('div.foo label') instead
var labels = jQuery('label');
// loop throu all labels
labels.each(function() {
// get single label element
var label = jQuery(this);
// get the content (for example "TV:"
var labelContent = label.text();
// replace if the label matches
switch(labelContent) {
case 'TV:':
// if the label contains "TV:" replace the <label> with the <i> element
label.replaceWith('<i class="fa fa-film fa-2x"></i>');
break;
case 'Foo':
// if the label contains "Foo" replace foo with the <i> element
label.html('<i class="fa fa-film fa-2x"></i>');
break;
}
});
Edit:
Or as #cforcloud suggests a short Form like
// note: .html does just replace the string "TV:" but leaves the label element in the DOM, while replaceWith is the way to replace an element
// http://api.jquery.com/replacewith/
jQuery("label:contains('TV:')").replaceWith('<i class="fa fa-film fa-2x"></i>');

Categories