Why does my script create extra, unwanted links? - javascript

I have the following JavaScript which creates link dynamically based on a SharePoint list that is grouped by a column "Report Category". The code is working however, if there is a empty group but has data then it should create all the links and a link called "Others". I wonder why it's creating 2 links that are "Others" along with all the other links it should create. html uploaded here https://jsfiddle.net/ea8dyvyq/5/
<div class="nav-report-category">
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//$("table.ms-listviewtable td[class=’ms-gb’]").each(function() {
//$("table.ms-listviewtable td[class^='ms-gb']").each(function(){
$(".ms-listviewtable td[class^='ms-gb']").each(function(){
$(".ms-listviewtable td[class^='ms-gb']").length;
//$("table.ms-listviewtable td.ms-gb").each(function(){
//$("ms-gb.td").each(function(){
//Hide all Counts for Groups
//$(this).find("span:last").remove();
//alert('loop is working');
var mydiv = document.getElementsByClassName("nav-report-category")[0];
//var liTag = document.createElement('li');
//var aTag = document.createElement('a');
//aTag.setAttribute("href","yourlink.htm");
var str = $(this).text();
str = str.substring(str.indexOf(":") +1); //remove everything before :
str = str.substring(0, str.indexOf("(")); //remove counts
//str = str.substring(str.indexOf(":") + 1);
//$(this).find("span:last").remove();
//var RptCat = $(".ms-listviewtable td.ms-gb:first a:eq(1)").text();
//var grNameRaw = $(this).text().replace(RptCat+' :','');
//var grName = grNameRaw.substring(0,grNameRaw.indexOf('(')-1).replace(/s|xA0/g,'');
//aTag.innerHTML = $(this).text();
//aTag.innerHTML = str.trim();
//aTag.setAttribute('target', '_blank');
if (!str.trim() || str.trim() == null)
{
var liTag = document.createElement('li');
var aTag = document.createElement('a');
aTag.innerHTML = "Other";
}
else
{
var liTag = document.createElement('li');
var aTag = document.createElement('a');
aTag.innerHTML = str.trim();
}
aTag.setAttribute('target', '_blank');
//var href = $(this).attr('href');
var link = window.location.href + "&RC=" + str.trim();
aTag.setAttribute("href",link);
liTag.appendChild(aTag);
mydiv.appendChild(liTag);
//mydiv.appendChild(aTag);
//mydiv.appendChild(document.createElement ("span"));
//mydiv.appendChild(document.createTextNode (" "));
});
//alert('test');
});
</script>

Related

Use dropdown selection in URL

I'm following the answer here to use the selection from a dropdown in a URL. I am using asp.net core, using:
asp-page="/Page" asp-page-handler="Action"
To do the redirect
The script below (from the link above) works great, except if you select an item from the dropdown then select a different one (and on and on), it appends both to the URL.
<script>
$("[name=selectedAnalyst]").on("change", function () {
var analystId = $(this).val();
var accept = $(this).closest('td').next().find("a")[0];
var oldUrl = accept.href;
var newUrl = oldUrl + "&analystid=" + analystId;
$(accept).attr("href", newUrl);
})
I tried scrubbing the parameter in question (using params.delete) but it's not working:
<script>
$("[name=selectedAnalyst]").on("change", function () {
var analystId = $(this).val();
var accept = $(this).closest('td').next().find("a")[0];
var oldUrl = accept.href;
let params = new URLSearchParams(oldUrl.search);
params.delete('analystid')
var newUrl = oldUrl + "&analystid=" + analystId;
$(accept).attr("href", newUrl);
})
Is there a way to get the above script to work how I envision, or a better way to do this?
Thank you
it seems that
let params = new URLSearchParams(oldUrl.search);
params.delete('analystid')
does not work
I tried with the codes and it could work
<script>
$("[name=selectedAnalyst]").on("change", function () {
var analystId = $(this).val();
var accept = $(this).closest('td').next().find("a")[0];
var oldUrl = accept.href;
var a = oldUrl.indexOf("analystid");
console.log(a);
if (a == -1)
{
var newUrl = oldUrl + "&analystid=" + analystId;
}
else
{
var newUrl= oldUrl.substring(0, oldUrl.length - 1) + analystId;
}
console.log(newUrl);
console.log(oldUrl);
$(accept).attr("href", newUrl);
})
</script>
Building on what Ruikai Feng posted I think this is working:
$("[name=selectedAnalyst]").on("change", function () {
var analystId = $(this).val();
var accept = $(this).closest('td').next().find("a")[0];
var oldUrl = accept.href;
var a = oldUrl.indexOf("analystId ");
if (a == -1) {
var newUrl = oldUrl + "&analystId =" + analystId ;
}
else {
var newUrl = oldUrl.substring(0, a - 1) + "&analystId =" + analystId;
}
$(accept).attr("href", newUrl);
})

JS window.location issue

I use this code for a redirection form when selecting a different jersey from the select input but while the JSfiddle works at my site there is no redirection from the window.location command.
https://jsfiddle.net/giorgoskey/95k1tc0b/4/
function populateSecondTextBox() {
var p = document.getElementById('your_name');
var txt = document.getElementById('txtFirst');
p.textContent = txt.value;
}
function populateNumberTextBox() {
var p = document.getElementById('your_number');
var txt = document.getElementById('txtSecond');
p.textContent = txt.value;
}
var goBtn = document.getElementById("goBtn");
var shirts = document.getElementById("shirts");
goBtn.onclick = function() {
window.location = shirts.value;
}
Hou have to use history.pusthState()
MDM
history.pushState(state, title [, url])
empty state and title.
window.history.pushState({}, '', url);
in your case
var goBtn = document.getElementById("goBtn");
var shirts = document.getElementById("shirts");
goBtn.onclick = function() {
window.history.pushState({}, '', shirts.value);
}

Remove items from a list if they exist and repopulate the list

I have some code that builds elements of a list on a sidebar. If a button is clicked I want to clear the list and repopulate it with new results. Right now the information just adds to the list. I would like to clear all of the items in the list so I can readd them.
function buildLocationList(data) {
for (i = 0; i < data.locations.length; i++) {
var currentFeature = data.locations[i];
var prop = currentFeature.locations;
var listings = document.getElementById('listings');
var listing = listings.appendChild(document.createElement('div'));
listing.className = 'item';
listing.id = "listing-" + i;
var link = listing.appendChild(document.createElement('a'));
link.href = '#';
link.className = 'title';
link.dataPosition = i;
link.innerHTML = '<b>' + currentFeature.company; + '</b>'
var address = listing.appendChild(document.createElement('div'));
address.innerHTML = currentFeature.address;
var csz = listing.appendChild(document.createElement('div'));
csz.innerHTML = currentFeature.csz;
/*var hours = listing.appendChild(document.createElement('div'));
hours.innerHTML = currentFeature.hours[0].days + ': ' + currentFeature.hours[0].hours;
hours.style.color = 'gray'; */
link.addEventListener('click', function(e){
// Update the currentFeature to the store associated with the clicked link
var clickedListing = data.locations[this.dataPosition];
// 1. Fly to the point
flyToStore(clickedListing);
// 2. Close all other popups and display popup for clicked store
createPopUp(clickedListing);
// 3. Highlight listing in sidebar (and remove highlight for all other listings)
var activeItem = document.getElementsByClassName('active');
if (activeItem[0]) {
activeItem[0].classList.remove('active');
}
this.parentNode.classList.add('active');
});
}
}
For your particular case, add this before you do anything else:
document.getElementById('listings').innerHTML = "";

JQuery with several Elements issue

i got an anchor in the DOM and the following code replaces it with a fancy button. This works well but if i want more buttons it crashes. Can I do it without a for-loop?
$(document).ready(buttonize);
function buttonize(){
//alert(buttonAmount);
//Lookup for the classes
var button = $('a.makeabutton');
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
//When class 'makeabutton' is found in string, build the new classname
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'+newButtonStyle
+'"><span class="left"></span><span class="body">'
+buttonContent+'</span><span class="right"></span></span>');
$('.buttonize').click(function(e){
if (linkTarget == '_blank') {
window.open(link);
}
else window.location = link;
});
}
}
Use the each method because you are fetching a collection of elements (even if its just one)
var button = $('a.makeabutton');
button.each(function () {
var btn = $(this);
var buttonContent = btn.text();
var buttonStyle = btn.attr('class');
var link = btn.attr('href');
var linkTarget = btn.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
...
};
the each method loops through all the elements that were retrieved, and you can use the this keyword to refer to the current element in the loop
var button = $('a.makeabutton');
This code returns a jQuery object which contains all the matching anchors. You need to loop through them using .each:
$(document).ready(buttonize);
function buttonize() {
//alert(buttonAmount);
//Lookup for the classes
var $buttons = $('a.makeabutton');
$buttons.each(function() {
var button = $(this);
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'
+ newButtonStyle
+ '"><span class="left"></span><span class="body">'
+ buttonContent
+ '</span><span class="right"></span></span>');
$('.buttonize').click(function(e) {
if (linkTarget == '_blank') {
window.open(link);
} else window.location = link;
}); // end click
} // end if
}); // end each
}

How to add rel='bookmark'?

I'm new here and I'm also not much of a programmer but I hope you guys could help me with Javascript.
You see, I have this 3rd-party script that enables bloggers blogging on Blogger to add some kind of a list of related posts on their pages. Here is the script:
<script type='text/javascript'>
//<![CDATA[
// takes a json feed and creates an HTML-formatted list of the elements
function RelatedPostEntries(json) {
// change the next three variables as required
var homeUrl = 'http://whatever.blogspot.com/';
var maxNumberOfPostsPerLabel = 7;
var TargetElement = 'relatedcontent-list';
var ul = document.createElement('ul');
var maxPosts = (json.feed.entry.length <= maxNumberOfPostsPerLabel) ? json.feed.entry.length : maxNumberOfPostsPerLabel;
for (var i=0; i<maxPosts; i++) {
var entry = json.feed.entry[i];
var alturl;
for (var k=0; k<entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
alturl = entry.link[k].href;
break;
}
}
var li = document.createElement('li');
var a = document.createElement('a');
a.href = alturl;
if(a.href!=location.href) {
var txt = document.createTextNode(entry.title.$t);
a.appendChild(txt);
li.appendChild(a);
ul.appendChild(li);
}
}
for (var l=0; l<json.feed.link.length; l++) {
if (json.feed.link[l].rel == 'alternate') {
var raw = json.feed.link[l].href;
var label = raw.substr(homeUrl.length+13) + ':';
var txt = document.createTextNode(label);
var h = document.createElement('b');
var div = document.createElement('div');
div.appendChild(h);
div.appendChild(ul);
document.getElementById(TargetElement).appendChild(div);
}
}
}
function CodeHook(url, label, callback) {
var script = document.createElement('script');
script.setAttribute('src', url + 'feeds/posts/default/-/' + label + '?alt=json-in-script&callback=' + callback);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
}
//]]>
</script>
The script works fine but the problem is the original programmer has forgotten to add rel='bookmark' to his codings thus leaving us bloggers with a huge headache when it comes to SEO.
Can you guys show me where and how to add that rel attribute?
Thanks.
Try putting a.rel = 'bookmark' after when the element is declared, around here:
...
var li = document.createElement('li');
var a = document.createElement('a');
a.href = alturl;
a.rel = 'bookmark';
...
I think this will work.
var a = document.createElement('a');
a.href = alturl;
a.rel = "bookmark";

Categories