I have a unordered list looking like this:
<ul id="frozen" data-name="nameOfSelect" class="tagit">
<li class="tagit-choice" tagvalue="2" style="padding-right: 4px;" id="tag-2">
<div class="tagit-label" data-value="2">kázeň</div>
</li>
<li class="tagit-choice" tagvalue="1" style="padding-right: 4px;" id="tag-1">
<div class="tagit-label" data-value="1">žalmxxxx</div>
</li>
</ul>
I need to bind an click function to all of them and get the data of the id="tag-1" to be used in the function.
I have tried this:
$('#[id|="tag"]').each(function(){
var tag = this.attr('id');
var tagID = tag.replace('tag-','');
this.click(function (){
alert('index.php?s=taglist&tag=' + tagID);
//window.location = string;
});
});
However, for some reason it seems that this approach is wrong for the <li> element as I am having problems with the selector (it seems). Maybe I am also missing something stupid... Any ideas?
No need for a loop, jQuery does this internally, and this is a native DOM element, which has an id property, but no attr() method :
$('[id^="tag-"]').on('click', function() {
var tag = this.id,
tagID = tag.replace('tag-', '');
alert('index.php?s=taglist&tag=' + tagID);
});
Related
I'm trying to compare the value of a tag obtained by query selector in the DOM with a given variable.
So far I've only managed the use of "contains" function, but I need to compare with an equality function.
The DOM element I need to obtain is "span:badge" and the variable to compare is "current_id".
This is the code I need to change:
var $a = $('span.badge:contains("' + current_id + '")').closest('a');
JS:
$(document).ready(function() {
"use strict";
var current_id = window.location.pathname.replace('/califications/','');
if (Number.isInteger(parseInt(current_id, 10))){
var $a = $('span.badge:contains("' + current_id + '")').closest('a');
$($a).addClass('active');
}else{
$('#middle_column > div > h1').html("No kid selected");
}
});
HTML:
<ul class="nav nav-pills flex-column" id="kid_list">
<t t-foreach="kids" t-as="kid">
<li class="nav-item">
<a t-attf-href="/califications/{{kid.id}}" t-attf-class="nav-link"><t t-esc="kid.name"/>
<span class="badge badge-pill float-right" style="display: none;"><t t-esc="kid.id" /></span>
</a>
</li>
</t>
</ul>
Thanks for reading!
To use contains seems right, but you need to do further, because contains also matches aa and ab if you search for a.
const $badges = $('span.badge:contains(`${current_id}`)');
const targetEl = null
$badges.each((i, e)=>{
if(e.text() === current_id){
targetEl = e.
}
})
targetEl should be what you need, or you will also do targetEl.closet("a") if you want to get the a.
You can use the selector which contains t-attf-href attribute ends with the id
$(`[t-attf-href$="${current_id}"]`).addClass('active');
Example:
var id = 'kid_id';
$(`[t-attf-href$="${id}"]`).addClass('active').text('test');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a t-attf-href="/califications/kid_id" t-attf-class="nav-link"><t t-esc="kid.name"/>
<span class="badge badge-pill float-right" style="display: none;"><t t-esc="kid.id" /></span>
</a>
Note: The .text('test') part is just for testing
Solution of the problem found.
var current_id = window.location.pathname.replace('/califications/','');
if (Number.isInteger(parseInt(current_id, 10))){
var $b = $('span.badge');
$b.each(function( index ) {
var badge_value = $( this ).text();
if (badge_value == current_id){
var active_a = $( this ).closest('a');
$(active_a).addClass('active');
}
});
}else{
$('#middle_column > div > h1').html("No kid selected");
}
Thanks for all the responses!
I have this html:
<ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px">
<li role="presentation" data-bind="attr : {'data-id' : ID , 'data-childCount' : Children().length}" style="padding-left: 20px; padding-right: 20px; text-align: center; color: white" class="active-li">
<label id="menu1" data-toggle="dropdown" data-bind="text: Name"></label>
<ul class="dropdown-menu" data-bind="foreach: Children" role="menu" aria-labelledby="menu1">
<li role="presentation"><a role="menuitem" data-bind="text: Name, attr: { 'href': Url} "></a></li>
</ul>
</li>
</ul>
That creates my menu on top using knockoutjs, it works perfectly and href attribute on a tag is filled correctly like href="/site/models#{"catId": "76b4a8ed-1350-46af-8184-3b68029cbd22"}" however when i click on the item, it doesn't redirect to new page. my first thought was maybe its because of hash but it wasn't, so i tried to use target attribute for any of the _self and all others it doesn't work. so my next guess was that there is a javascript method overriding this, so far i haven't found anything. so my question is why doesn't it work?
KnockOut ViewModel:
landing.dataModels.Category = function (_id, _categoryTypeId, _name, _description, _parentId, _children) {
var self = this;
this.ID = ko.observable(_id);
this.CategoryTypeId = ko.observable(_categoryTypeId);
this.Name = ko.observable(_name);
this.Description = ko.observable(_description);
this.ParentId = ko.observable(_parentId);
this.Url = ko.computed(function () {
return '/site/models#{"catId": "' + self.ID() + '"}';
});
this.Children = ko.observableArray([]);
this.getChildren = ko.computed(function () {
return self.Children();
});
_.each(_children, function (item) {
self.Children.push(new landing.dataModels.Category(item.ID, item.categoryTypeId, item.Name, item.Description, item.ParentId, item.Children));
});
};
Update
I have to say that when i right-click on the item and open in new window it does work and shows the page, but its not working on direct left click.
Probably the problem is in the quotes in the generated URL:
href="/site/models#{"catId": "76b4a8ed-1350-46af-8184-3b68029cbd22"}"
The value for href is actually "/site/models#{" leaving the rest of the URL as invalid HTML.
You could try to bind to the escaped URL:
this.Url = ko.computed(function () {
return encodeURI('/site/models#{"catId": "' + self.ID() + '"}');
});
Finally i got tired and i just went with a simple jquery click to make it work:
$(document).ready(function () {
setTimeout(function () {
$(document).on("click", ".ilia-catLink", function () {
var a = $(this).attr("href");
window.location = a;
});
}, 100);
It works this way, but i still wonder why wouldn't that href work on itself.
I have a control which allows users to sort the <li> in whatever order they want. when the form submits I want to grab the text inside the <li> for each <li> put into an array, in the order on the form.
<ul id="sortable">
<li class="ui-state-default">
<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Protective Services
</li>
<li class="ui-state-default">
<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Engineering Services and Public Works
</li>
</ul>
I am grabbing the <li>'s with:
var ar = [];
ar = document.getElementById("sortable").getElementsByTagName("li");
I then go through the array:
for(i = 0; i < ar.length; i++){
alert(ar[i].text()); //ar[i].anything results in console errors.
}
ar[i] displays [object HTMLLIElement] for every <li> available.
if I try to access the .text/.val/id properties inside the items i get a console error. So I'm assuming this has to do with a parsing/conversion issue?
How do I properly create an array that looks like protective services,Engineering Services and Public Works and NOT like [object HTMLLIElement],[object HTMLLIElement]? Or how do I access my text information from the <li> as a [object HTMLLIElement]?
For a pure javascript solution use the innertext property
alert(ar[i].innerText);
Fiddle: http://jsfiddle.net/3fjursaw/
You need to get the jQuery object in order to use text():
alert($(ar[i]).text());
JSFIDDLE: http://jsfiddle.net/rh6ufn23/1/.
You need to use the properties ar[i].innerText or ar[i].textContent on DOM nodes. The method .text() would be used if you had a jQuery object
var lis = document.getElementById("sortable").getElementsByTagName("li");
var data = [];
for(var i=0; i<lis.length; i++){
data.push(lis[i].innerText);
}
var jsonFormated = JSON.stringify(data);
document.getElementById("log").innerHTML = jsonFormated;
<ul id="sortable">
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Protective Services</li>
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Engineering Services and Public Works</li>
</ul>
<div id="log"></div>
the problem is that you work with the HTMLElement, which is of vanilla js, not jQuery. Try .innerHTML instead of .text()
Use :
var ar = [];
var listItems = $("#sortable li");
listItems.each(function(li) {
ar.push($(this).text());
});
Working here: http://jsfiddle.net/csdtesting/0uddfms6/
jQuery solution:
$('li', '#sortable').each(function(){
alert($(this).text());
});
Or to fix your solution in pure JS:
var ar = [];
ar = document.getElementById("sortable").getElementsByTagName("li");
for (i = 0; i < ar.length; i++) {
alert(ar[i].innerText);
}
See fiddle.
I have an HTML structure as:
<div title="" class="interestareascategories_chn chzn-container chzn-container-multi">
<ul id="ul_deptType" class="chzn-choices">
<li id="li_dept_1" ver="old" class="search-choice"> <span>DEV</span> <a rel="3" class="search-choice-close" seq="1" href="javascript:void(0)"></a>
</li>
<li id="li_dept_2" ver="old" class="search-choice"><span>QA</span> <a rel="3" class="search-choice-close" seq="2" href="javascript:void(0)"></a>
</li>
<li id="selD7J_chzn_c_3" class="search-choice"><span>sag</span> <a class="search-choice-close" seq="0.19415735425269753" href="javascript:void(0)"></a>
</li>
<li class="search-field"><span contenteditable="true" style="width: 25px;"></span>
</li>
</ul>
</div>
How to get only seq in anchor tag which have rel attribute?
Here's a fairly simple and straightforward answer:
// gets all anchors with attribute rel and place their [seq] values into an array
var values = $.map($('a[rel]'), function(el){
return el.getAttribute('seq');
});
console.log(values); // ["1", "2"]
live code sample
var seq = $("a[rel]").attr("seq");
Try this:
var anchor = $('a[rel][seq]'); // this only targets anchors which have these
// rel and seq attributes.
You can try this:
$('a[rel][seq]').on('click', function () {
alert($(this).attr('seq'));
});
Fiddle
You can use next selector for specific rel value
var seq3 = $("a[rel='3']").attr("seq");
To get sum of all sequences use next:
var sum = 0;
$.each($("a[rel='3']"), function(i, el)
{
sum += el.getAttribute("seq") | 0
})
jQuery(document).ready(function(){{
var check=jQuery(".search-choice a ").attr("rel");
if(check!="undefined")
{
var selVar=jQuery(this).attr("seq");
}
})
you should write a script like this, you can also store all "seq" value in an array.
You you want seq attribute of all anchors that have rel attribute then:
try like this:
$("a.search-choice-close").each(function(){
if($(this).attr('rel')) {
alert($(this).attr('seq'));
}
})
or :
$("a.search-choice-close[rel]").each(function(){
alert($(this).attr('seq'));
})
demo fiddle1
demo fiddle2
You can use something like:
http://jsfiddle.net/U2s7f/1/
$("a[rel]").map(function(i, el) { return $(el).attr("seq"); })
You can use an has attribute selector for rel and the get the value of seq attribute on the selected elements.
Code:
$('a[rel]').each(function(i,e){
console.log($(this).attr('seq'))
});
Demo: http://jsfiddle.net/IrvinDominin/VU3hr/
I'm newbie with javascript and bad English either .
1)I have HTML like this:
<ul id="search-list" class="playlist1">
<li class="song songW" data-song-id="70">
<div id="songNum" class="songNum" songurl="music/turn-it-up.mp3"
songtitle="Turn It Up">Turn It Up
</div>
</li>
<li class="song songB" data-song-id="83">
<div id="songNum" class="songNum" songurl="music/black-keys.mp3"
songtitle="Black Keys">Black Keys </div>
</li>
</ul>
2) I use this Javascript to get attribute from the clicked DIV have class or id = "songNum" :
var el = $("ul#search-list");
$(el).bind(".songNum").click(function(eve) {
eve.preventDefault();
songUrl = $(this).attr("songurl");
alert(songUrl);});
///// It's return "Undefined"
3) And when i change
var el = $("ul#search-list");
$(el).bind(".songNum").click(function(eve) {
eve.preventDefault();
songUrl = $(".songNum").attr("songurl");
alert(songUrl); });
///// It's just return a atrribute of the first DIV =>"music/turn-it-up.mp3", even i was click on the second DIV
Please help me, show me my mistake !
Thanks alots !!!
var el = $("ul#search-list li");
$(el).bind(".song").click(function(eve) {
eve.preventDefault();
songUrl = $(this).find('div').attr("songurl");
alert(songUrl);
});
should work. Use $(this) to have the context of the first div which is clicked, than find the child div inside and then you could access its properties.
Hope that helped