Replacing an Element in jQuery [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to modify an element in jQuery programmatically, i.e. a number in docID increments up to a maximum number. I'm replacing text on a series of images on a page from Download to View. If I use #ctl00_cphMainContent_dlProductList_ct100_ctl00_lnkProofDownload instead of docID in the $(docID).text(...) part of the code, the text gets replaced correctly. When I use the docID variable in its place, it doesn't work.
What am I doing wrong here?
Thanks.
var max = 10;
var count = 100;
var s1 = "#ctl00_cphMainContent_dlProductList_ct";
var s2 = "_ctl00_lnkProofDownload";
var docID = "";
for (i = 1; i <= max; i++)
{
docID = s1.concat (count++, s2);
$(document).ready(function() {
$(docID).text(function(i, oldText) {
return oldText === 'Download' ? 'View' : oldText;
});
});
}
This is the HTML code that is being modified. The word Download is replaced by View.
<a id="ctl00_cphMainContent_dlProductList_ctl00_ctl00_lnkProofDownload"
href="../../../Controls/StaticDocProof.ashx?qs=op/5WlcUxeg849UT973Mwf0ZnNcMLfe3JYAe7EnJORsdyETYV1vcKaj0ROc2VrN5fXfYjO2MM6BUYXzX2UKmog=="
>Download</a>

It looks like you have done a couple things incorrectly in your code, including using a 1 instead of an l. If it was supposed to be a 100 instead of a l00, something more like this would work:
jQuery(function () {
var max = 10,
count = 100,
s1 = 'ctl00_cphMainContent_dlProductList_ct',
s2 = '_ctl00_lnkProofDownload',
docID;
for (var i = count; i <= count + max; i++) {
docID = s1 + i + s2;
jQuery('#' + docID).text(function (idx, oldText) {
return oldText === 'Download' ? 'View' : oldText;
});
}
});
Fiddle here: http://jsfiddle.net/ochguL2d/
Otherwise, let us know if it is supposed to be l00 for a different answer.

Your a element has this in the middle (note two "els"):
ctl00_ctl00
… but your docID has this in the middle (note a "one and an el"):
ct100_ctl00
Fix your HTML, and your code works as-is: http://jsfiddle.net/5c7hwyts/
However, that's an odd way to write jQuery.
Here's a different approach:
$('a').text(function(i, oldText) {
var num= parseInt(this.id.split('ctl00_cphMainContent_dlProductList_ct')[1]);
if(num>=100 && num<110) {
return oldText === 'Download' ? 'View' : oldText;
}
});
Fiddle

The element IDs your are trying to match in your code are not the ones in the DOM.
// This is what you want to match
var domID = "#ctl00_cphMainContent_dlProductList_ct100_ctl00_lnkProofDownload"
^ that is an L
// this what your code is trying to match in its first iteration
var docID = "#ctl00_cphMainContent_dlProductList_ct10_ctl00_lnkProofDownload";"
^ that is a 1 (one)
Also, your code's max variable needs to be a two char numeric string with leading zeros starting at zero, not an integer starting at 10.
Personally, I would just:
// On DomReady...
$(document).ready(function() {
// loop through all anchors that have "lnkProofDownload" in their ID attribute
$('a[id*="lnkProofDownload"]').each(function() {
// and if the text is set to "Download", change it to "View"
if ($(this).text() == "Download") {
$(this).text("View");
}
});
});

Related

Coloring the same elements in a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I work with JavaScript on my bachelor thesis.
I would like to read a string and mark the elements that are the same and follow each other in the same color.
I have not found a good approach yet.
I would be grateful for a good proposal.
This is what i have right now.
function colorsetting(input){
var collength = input.length;
var now = '', last2 = '', colored = '';
now = last2 = input[0];
for(var i = 1; i <= collength, i++){
if(now !== last2){
colored = last2.fontcolor("green");
last2 = now;
}
now = input[i];
}
colored = last2.fontcolor("red");
return colored;
}
You can split up your input string using a regex:
/(.)\1*/g
(.) grabs any character, and stores that in capture group 1.
\1* then tells the regex to match as many of those as it can.
Then, iterate over that array, wrap the strings in a span, each with their own colour.
const str = "aaaabbbb123aaaaccccz";
const result = str.match(/(.)\1*/g);
console.log(result);
result.forEach(t => {
// Create a span element
const span = document.createElement("span");
// Set the text in that span to be the current match
span.innerText = t;
// Set the span's color to something random.
span.style.color = "#"+((1<<24)*Math.random()|0).toString(16);
document.body.append(span);
})
(random color code from here)

split html text by some special tags [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have description with html format. But it need to display in one line. And at the end of line, we need to display '...' when it's too long. I tried to use css, some thing like :
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
It worked. but when I put some html tags such as p, div. It can not work any more. It displayed more than one line :(.
I tried to use javascript also, split html text by regex pattern, I used this pattern /</?[^>]+>/g, but it also remove some tags: b..., but I don't want it. i just want to remove div, br, p, table...
So could you give me some idea. Thanks.
Try split join:
"some text <br />".split("<br />").join("");
if you have variable tags you may should try something like this:
var tagString = "someText<div class='someClass'><b><h1>someText<h1><br /></b></div>";
var noTagString = "";
var lastIndex = 0;
var dontRemove = ["<b>", "</b>"];
// iterate over the tagged text
for(var i = 0; i < tagString.length; i++){
// check for '>'
if(tagString[i] === "<"){
// if '<' is found
noTagString += tagString.substring(lastIndex, i);
// take the left over
var leftOver = tagString.substr(i, tagString.length);
var goOn = false;
// check for tags to keep
for(var k = 0; k < dontRemove.length; k++){
if(leftOver.startsWith(dontRemove[k])){
goOn = true;
break;
}
}
if (goOn){
// we found a tag we want to keep so go on
continue;
}
// iterate over the left over
for(var j = 0; j < leftOver.length; j++){
// if closing tag is found
if(leftOver[j] === ">"){
// update i and last index
i = i + j;
lastIndex = i + 1;
break;
}
}
}
}
this is not tested to well but maybe it points you in the right direction.
Put the tags you want to keep in the dontRemove array.

jquery hide/show or condiiton failing

Is there anything wrong with the jQuery/JS below? I have an input field aAmt which on change calls below. ${dAmt} = "10000" from DB. It basically converts the number to $ format(eg.. 23 to $23.00) and focuses the value to the input field. Issue is the if loop (if(aAmt >= a_amount)...) fails.
Even if the condition fails it goes to if loops and shows the div which should not happen. I don't see any error in developers console.
$('#aAmt').change(function() {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
curFormat(aAmt);
if(aAmt >= a_amount)
{
$("#dsDiv").show();
}else{
$("#dsDiv").hide();
}
});
function curFormat(aAmt)
{
var nAmt = Number(aAmt.replace(/[^0-9\.]+/g,""));
var fAmt = '$' + nAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
document.getElementById("aAmt").value = fAmt;
}
Have you tried to convert a_amount to an int, to be sure to compare two integers together:
var a_amount = parseInt("${dAmt}");

Creating a Script To Increase Numbers On Website [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
We have a website, on the front page we show "Parcels Shipped", we'd love the numbers to updated via a formula - i.e. we shipped 34,502,233 parcels in 2014... We show a static stat.... But we'd love to have the numbers increased via a formula that increases the number by the second/minute
Thanks for all the replies guys - So we current have this: gyazo.com/d421a3675884e2610d368c9e60e8acca
we want it to increase around 76 times per minute.... so a rotating number basically - i've no idea how to achieve this. (left number) & We want it to increase around 43 times per minute for middle number
Does anyone know where I can find this sort of trick?
This achieves your desired functionality using setInterval() to fire a function that checks to see how long it's been since today. Then, multiplying by the increase you mentioned in the comments and adding it to the numbers in your screenshot.
JS:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function timeSince() {
var prevTime = new Date(2015,8,8,0,0);
var thisTime = new Date();
return (thisTime.getTime() - prevTime.getTime()) / 1000;
}
function parcelCount() {
var secDiff = timeSince();
var leftNum = document.getElementById("left");
var midNum = document.getElementById("mid");
var leftNumCount = Math.round(((76/60) * secDiff) + 40093794);
var midNumCount = Math.round(((43/60) * secDiff) + 22874098);
leftNum.innerHTML = numberWithCommas(leftNumCount);
midNum.innerHTML = numberWithCommas(midNumCount);
}
parcelCount();
setInterval(parcelCount, 1000);
HTML:
<h3>Left</h3>
<span id="left"></span>
<h3>Mid</h3>
<span id="mid"></span>
Demo: http://jsfiddle.net/hopkins_matt/513ng07d/
Used info from these answers to build this:
https://stackoverflow.com/a/2901298/4556503
https://stackoverflow.com/a/6636639/4556503
Use setInterval with the increasing function as 1st argument and ms as the 2nd one.
var el = document.getElementById('counter')
var x = 0
window.setInterval(function(){
el.value = formula(++x)
}, 1000)
If the increase is completly random, just a "front-end design stuff" (sorry, guys), you can use setInverval() from Javascript.
It works this way:
every _s ms, the function will be called. If you have an increase factor, like a global constant you could do something like:
var myDiv = document.getElementById("myId");
var _mseconds = 1500; // mileseconds
var incFactor = 150;
var handlerInt = setInverval(function() {
myDiv.innerHTML = incFactor+incFactor; // you can use Math.Random() or something, instead
}, _mseconds);
Hope it helps!

Check if number is between 2 values

I am currently building a filter based on div class's and contents.
I was wondering if it is possible to pass a string like follows into a function:
"£0.01 - £100.01"
and then have the function show all div's where the html of that div is between this range
so say I have a div with a class of "price" and its contents were: £10.30
from running this function and passing the string of "£0.01 - £100.01" into it it would hide all div's similar to how I have done it in the js below then only show the div's where the div class "price"'s contents were within the selected price range.
I have managed to do something similar with a brand filter which I will provide here:
function brand(string){
var brand = string;
$('.section-link').hide();
$('.section-link').children('.brand.' + brand).parent().show();
if (brand == "All Brands"){
$('.section-link').show();
}
}
Any general advice or code is greatly appreciated to help achieve this :)
Thanks,
Simon
Edit:
Target div example:
<div class="section-link">
<div class="price"> £56.99</div>
</div>
Reply's are helping a lot, the filter function looks awesome so thanks for pointing that out.
I am just trying to find a way to split the initial string being past in, into two values one low and one high as well as stripping the £ signs
Edit:
managed to split the original string:
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
alert(rangearray[0]);
alert(rangearray[1]);
FINAL EDIT:
From the reply's I have kind of been able to make a function, however it is not entirely working :) can anyone spot what I have done wrong?
function price(string){
$('.section-link').hide();
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
low = rangearray[0];
high = rangearray[1];
$('.section-link').children('.price').each(function() {
var divprice = $(this).text().replace(/\u00A3/g, '');
if (low <= divprice && high >= divprice){
$(this).parent().show();
}
})
}
Okay its working, I had spaces in my string. The final function (although messy :P) is:
function price(string){
$('.section-link').hide();
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
low = rangearray[0].toString();
high = rangearray[1].toString();
lowmain = low.replace(/ /g,'');
highmain = high.replace(/ /g,'');
$('.section-link').children('.price').each(
function() {
var divprice = $(this).text().replace(/\u00A3/g, '');
var maindivprice = divprice.replace(/ /g,'');
if (lowmain <= maindivprice && highmain >= divprice){
$(this).parent().show();
}
})
}
I'd use a function like this one, where range is the string you gave
function highlightDivs(range) {
var lower = range.split(" ")[0].slice(1);
var upper = range.split(" ")[2].slice(1);
$('.section-link').hide();
$('.section-link').children('.price').each(function() {
if (lower <= $(this).val() && upper >= $(this).val()){
$(this).parent().show();
}
});
}
You can use jQuery's build in filter() function, and write a filter with the condition you described.
First, you should hide all the items with any price.
$(".price").parent().hide();
Then, you can filter all the items with in-range prices and show them:
$(".price").filter(function(){
var $this = $(this);
var value = $this.val();
return (value >= minNumber && value <= maxNumber); // returns boolean - true will keep this item in the filtered collection
}).parent().show();
Use jQuery's filter()
An example -> http://jsfiddle.net/H6mtY/1/
var minValue = 0.01,
maxValue = 100.01;
var filterFn = function(i){
var $this = $(this);
if($this.hasClass('amount')){
// assume that text is always a symbol with a number
var value = +$this.text().match(/\d+.?\d*/)[0];
if(value > minValue && value < maxValue){
return true;
}
}
return false;
};
// apply your filter to body for example
$('#target span')
.filter(filterFn)
.each(function(i,ele){
// do something with the selected ones
$(this).css('color','red');
});
I would go by something like:
Get all the divs that have prices.
Iterate through all:
Transform the strings (minus the pound symbol) to float numbers and compare with an IF statement if they are inside the provided range.
If they are just go to the next (use continue maybe)
Else (not in the range) add a class like .hide so it can be blended through css (or just use the blend function from jquery)

Categories