Change Text of Array Of links in jQuery - javascript

For my school's website they have a dropdown list of courses that you're currently enrolled in on the home page. However, if you see it, it is cluttered full of letters that many people might not want to see.
I already know how I'm going to do this. I'm going to use jQuery to select each list item:
var links = $(".d2l-datalist li .d2l-course-selector-item .d2l-left .vui-link");
This returns an array of <a> elements in text form.
Using links.text("Boo!"); I can set the text of all of them to "Boo!", but I want to change each one individually, using a for/in loop to itterate through each <a> and change the text depending on what the value of the href is.
However, whenever I do this, since the items in the array are strings, I cannot do anything to them with jQuery.
Any help with this is appreciated :)
Here's my code so far (running from a $.getScript() from a JS bookmarklet):
var links = $(".d2l-datalist li .d2l-course-selector-item .d2l-left .vui-link");
//links.text("Boo!");
var count = 1;
for (var link in links) {
link.text("Boo #" + count);
count += 1;
}
Relevant markup: http://hastebin.com/ulijefiqaz.scala

You can use the jQuery .each iterator function.
var links = $(".d2l-datalist li .d2l-course-selector-item .d2l-left .vui-link");
var count = 1;
links.each(function() {
$(this).text("Boo #" + count++);
});

Related

How to dynamically get the dynamically created ID in a li

I've been trying to learn js (and a tad of jquery) and I have run into two difficulties when trying to find a way to combine solutions that I find.
Just a little warning that this code is a mix of a few tutorials that I have recently done. I am very new to js.
So I start with a basic html with a few li.
<body>
<ol id="liste">
<li class="active">
</li>
<li>
</li>
<li>
</li>
</ol>
<div id="main_ima">
</div>
<script src="js/main.js"></script>
</body>
I want to create ids for each "li" so in my main.js I add this:
var idVar = $("#liste").find("li").each(function(index){
$(this).attr("id","num-li-"+index);
});
This works great so far. Everytime I add a new li, it gets a new id. I also put it into a var because I will need to use it later.
In th console, If I type idVar, it gives me the whole list of li. If I type idVar[3]. it only gives me the li associated to the [3]. Perfect.
Now I want to get something to appear when one of the li is clicked. For example, I will use the [3]. So I add this to my main.js
var imaContainer = document.getElementById('main_ima')
var listed = document.getElementById('liste');
idVar[3].addEventListener("click", appar);
function appar(){
$(idVar[3]).addClass("active").siblings().removeClass("active");
var imaSel = new XMLHttpRequest();
imaSel.open('GET', 'https://domain.link.to.file.json');
imaSel.onload = function() {
var imaLo = JSON.parse(imaSel.responseText);
renderHTML(imaLo);
};
imaSel.send();
};
function renderHTML(data) {
var htmlS = "";
for (i = 0; i < data.length; i++) {
htmlS += "<p>" + data[i].name + " is a " + data[i].species + ".</p>";
}
imaContainer.insertAdjacentHTML('beforeend', htmlS);
}
Just a side note, I added the add/remove "active" class for CSS.
So when I click the li[3], it works almost as expected. The only thing is when I reclick [3] it produces the result a 2nd time. And again, if I click it a 3rd time, it produces the result a 3rd time, without remove the past results. (which is not totally what I want. Just the 1st result would be better.)
But that is not the main problem I am facing.
I would like the [number] to be dynamically detected, based on the id of the clicked li. I could, in a very ugly way, copy and past this code for every [number] I have. and it would work. But then, what if I want to add more li elements, I would need to add more copy and paste of the above code, giving me possibly huge files for nothing. This is surely not the best way, although it would work.
I'm sure this can be done dynamically.. but that is mostly why I am here. :)
Afterwards, once the dynamic has been added to the clicked li, I would also like the link to be changed dynamically based on the li id. For example, instead of :
imaSel.open('GET', 'https://domain.link.to.file.json');
something like:
imaSel.open('GET', "https://domain.link.to.file" + var +".json");
the var being equal to the [3] number of the clicked li.
In this case, when I try to add a var with a for loop, I always get the "var = max.length" instead of the "var = [id of clicked item]".
So there you have it. Do you need more details?
This is my first JS and/or Jquery try. I've been playing with it for a few days but when I search for answers, when I implement the "solutions" it alwas gives me some new problem. So I am showing you the code that is the closest, IMO, to what I am looking for.
Hopefully, I am not too far away of somehting that works and is not as big as my solutions. :)
Thanks for your time and all help is appreciated.
Here are some suggestions:
You don't need to assign id attributes to your li. You actually never need that id. This will work just as well (note also the > in the selector which makes the find call unnecessary):
var $li = $("#liste > li");
Already now you can address each of the li as $li[3], although that is not the "best practise". Better is $li.get(3). I also like the convention to start the variable with $ when it is the result of a jQuery selection. It gives a clue that you can apply jQuery methods to it.
You don't need to assign a click handler to each li separately. With jQuery on (instead of the native addEventListener) you can assign one event handler for all of them at once.
$li.on('click', apar)
The callback you define for on will have this set to the particular li element that has been clicked, so you can do:
$(this).addClass("active").siblings().removeClass("active");
... without any array lookup.
jQuery offers easy functions for several types of HTTP requests, so you don't need to use XMLHttpRequest. In fact, there is one specifically for getting JSON, so you don't even have to parse the response:
$.getJSON('https://domain.link.to.file.json', renderHTML);
The jQuery index() method can give you the sequence number of that li:
$.getJSON('https://domain.link.to.file' + $(this).index() + '.json', renderHTML);
To replace the inner HTML of a certain element, the jQuery html method can be used:
$('#main_ima').html(htmlS);
Note also how you don't need the DOM native getElementById method, jQuery can look that up for you with the short $('#main_ima').
Example
Here is a working example with a fake JSON serving server:
$("#liste > li").on('click', apar);
function apar() {
$(this).addClass("active").siblings().removeClass("active");
$.getJSON('https://jsonplaceholder.typicode.com/posts/'
+ (1+$(this).index()), renderHTML);
}
function renderHTML(data) {
// This particular JSON request returns an object with body property
var htmlS = data.body;
$('#main_ima').html(htmlS);
}
// On page load, click on the first `li` to automatically load the data for it
$('#liste > li:first').click();
#liste { width: 40px }
.active { background: yellow }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="liste">
<li class="active">load 1</li>
<li>load 2</li>
<li>load 3</li>
</ol>
<div id="main_ima"></div>
The following answers your main concern, how to dynamically get the ID with jquery:
$('.listen-to-me').click(function() { //Add event listener to class
var elementId = $(this).attr('id'); //Get the 'id' attribute of the element clicked
var idNumber = elementId.substring(elementId.indexOf("-") +1); //Get the index of the "-" in the string, and then cut everything prior
alert(idNumber); //The final result
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="test-1" class="listen-to-me">1</li>
<li id="test-2" class="listen-to-me">2</li>
<li id="test-3" class="listen-to-me">3</li>
<li id="test-4" class="listen-to-me">4</li>
<li id="test-5" class="listen-to-me">5</li>
</ul>

change part of a link with javascript in a specific div only

Hi I need to edit some links on a page. Using the below code works but causes other problems on the page. I need the code to only affect elements with a certain input id. I also can't just replace the links as a query will be dynamically added to the end of each link. So in summary i just need to replace parts of all links with an input id "btnViewDetails". Any help would be great I'm very stuck. Cheers
<script language="javascript">
document.body.innerHTML = document.body.innerHTML.replace(/JobSeekers/g,'mobile');
document.body.innerHTML = document.body.innerHTML.replace(/JobPositionDetail.aspx/g,'JobPositionDetail_Mobile.aspx');
</script>
var someVariable = document.getElementsByClassName('btnViewDetails');
(you should use class instead of ID, if it is not a unique value).
someVariable is now an array holding all elements with class name btnViewDetails.
Now replace the text you want to replace only on the href values of you elements (you will have to loop over them):
for (i = 0; i < someVariable.length; i++) {
someVariable[i].href // do your replaces here
}

How to make action (hide) on all table cells, which ID is not containing some string

I got whole table, which has cells with particular ID's, example: "2012-01-01_841241" etc etc. Date, then some number.
I want to filter my table, so I send some request and get for example three numbers which should be only shown.
I want to hide all cells without these numbers in their IDs - is it any other way than iterating over all of them and check if their ID matches my ID string? (It looks costly).
So, i'm trying to avoid it (especially, when I will have a table of someNumbers :) ):
$('td').each(function(){
if($(this).attr("id") != someNumber) $(this).hide();
})
Thanks!
Well here is a way you can do it (jsFiddle here):
Essentially you can hide everything then make the ones you want visible:
$("#myTable td").hide();
showCells("2012-01-01_841242", "2012-01-01_841247");
function showCells() {
for (var i = 0; i < arguments.length; i++)
{
$("#" + arguments[i]).show();
}
}
The problem however with doing this on a table is that you can end up with an uneven number of <td> tags inside your various <tr> tags so you may want to find a different way to lay them out.
Did you consider something like this:
You can alway hide all tds and than show only these which you want to show
var id = getCurrentIdNotToHide();
$('td#'+id).show();
But I'm not sure if this is better solution
Use this code:
$('td:not([id="' + someNumber + '"])').hide();

Append and remove values in a link

So I am using http://isotope.metafizzy.co to filter out different items on a site. The menu should be a "build up" type where when one category is clicked, it filters to those categories, when the next is clicked it adds those newly clicked categories to the existing filter of categories. When its clicked a second time it should remove that categorie from the filter.
More specifically, I have href with #filter and data-filter=".category-name" I need to have a function that would add ", .another-category" to the end of data-filter value for each of the links with name="filters" (or i can use a class instead of if easier)
<ul>
<li>Kitchens</li>
<li>Bathrooms</li>
<li>Living Rooms</li>
<li>Bedrooms</li>
</ul>
I know this function is wrong and doesnt work but its just some pseudo-code
function addFilter(filter) {
names = document.getElementsByName("filters");
for (var name in names) {
name.data-filter = "existing filter, " + filter; // this should be appended to all data-filters
}
}
so basically when a link is clicked it both filters to that category only (lets say kitchens), but also adds the category to the rest of the data-filters (.bedrooms, .kitchens)
javascript or jquery or anything else i may have not realized could work. the documentation for isotope has the option to filter multiple groups of items, but I need it to filter combinations of individual items. Maybe its possible to modify their combination filters to items instead of groups?
See the following article as placed in this post. It should put you in the right direction.
http://www.queness.com/post/7050/8-jquery-methods-you-need-to-know
Stackoverflow question
jQuery - How to add HTML 5 data attributes into the DOM
Well you tagged jQuery, which makes this easy, but I only see you using JS. Anyway, here's one way and some extra info, hope it helps:
jsFiddle {with replication}
jsFiddle {without}
Script
$('li a[name="filters"]').on("click", function(e) {
e.preventDefault();
$(this).data("filter", $(this).data("filter") + ".another-category");
/* and if i wanted to do it without replicating already existing info:
var f = $(this).data("filter");
if (f.indexOf(".another-category") == -1) f += ".another-category";
$(this).data("filter", f); */
});
HTML
<ul>
<li>Kitchens</li>
<li>Bathrooms</li>
<li>Living Rooms</li>
<li>Bedrooms</li>
</ul>
X-tra NFO
jQuery.data(): Biggest Deference - Returns the value that was set
jQuery's .data(): Biggest Deference - Returns the element that was manipulated

IE8 not displaying JSON data using JQUERY in a list

I'm developing an asynchronous database searching tool. It currently works with firefox and chrome, but has one enormous hiccup with internet explorer (version 8).
Students can enter their prospective MCAT and GPA scores and then jquery sorts out the schools where they place in the top 25% or the middle 50%. Basically, it's a neurotic premed student's dream (or nightmare).
The jquery cycles through the JSON data, displaying each item that matches the criteria in a <li> item. Again, it works great in ff and chrome, but in internet explorer it refuses to display the list items. It does, however, display the proper count of items, which means that the json data is going through properly.
After searching through stackoverflow I saw some commentary (colorful, often!) on how IE refuses to allow placing elements in tables and some other innerhtml elements using jquery.
I'm wondering if this is the problem, and though I found a similar problem on this question I can't quite figure out how to adapt it for my project (I'm new to javascript).
Any help would be wonderful. The code can be found below.
-samuel
$.getJSON("schoolgrabber.php?jsoncallback=?", function(data){
//loop through the items in the array
for(var x=0; x < data.length; x++){
if( MCAT >= data[x].TopPercentileMCAT && data[x].TopPercentileMCAT!=''){
var li = $("<li>").appendTo("#schoollist");
var school= data[x].School;
//add the actual information into the li using a chain event
//the event begins by appending an <a> tag, with the name of the school inside (text(data[x].School)
//then it adds a unique id, which is the iteration number the counter is on above (x)
//then it adds the url, and adds the school variable, which allows the schools to be clicked over to the results page
//then it puts all of that inside li, as declared above (slightly backwards, but hey)
$("<a>").text(data[x].School).attr("id",x).attr("href", "results.php?school=" + school).appendTo(li);
$("#schoollist li").addClass("school");
var quantity = $(".school").length;
$('#schoolquantity').empty();
$('#schoolquantity').append(quantity);
}}
});
Instead of using jQuery and chaining to build up your DOM, try instead to build out a string of the HTML you want rendered and add that completed string just the one time.
Not only might it fix your bug, but you'll also get better performance. What I'm doing is building up the list's full HTML and calculating the quantity. Then, when I'm completely finished building the HTML, I add it to the DOM. IMO the way I have below is also more readable. Note that I haven't tested this, but you should get the idea:
$.getJSON("schoolgrabber.php?jsoncallback=?", function(data){
//loop through the items in the array
var html = [];
var parentElement = $("#schoollist");
var quantity = 0;
for(var x=0; x < data.length; x++){
if( MCAT >= data[x].TopPercentileMCAT && data[x].TopPercentileMCAT!=''){
var school= data[x].School;
html.push("<li class=\"school\">");
html.push(" <a id=\"" + x + "\" href=\"results.php?school=" + school "\">");
html.push( data[x].School);
html.push(" </a>");
html.push("</li>");
quantity++;
}
}
parentElement.html(html.join(""));
$('#schoolquantity').html(quantity);
});
Remember that everytime you alter the DOM the browser has to do a bunch of stuff to update the webpage. This is costly. You want to avoid adding/grabbing from the DOM as much as possible and instead "batch" your alterations (As a side note, if you want to alter the DOM alot without "batching", take a look at the jquery detach method).
Good luck, hope this works for you!

Categories