How to change number inside of div class and update it? - javascript

I'm trying to change the existing HTML code on a site. See the example below:
var multiplier = 1.5;
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0
})
//for first two occurences
var priceEls = document.getElementsByClassName("price");
for (var i = 0; i < priceEls.length; i++) {
var price = priceEls[i].innerText;
var priceN = getNumber(price)*multiplier;
alert("Price: " + formatter.format(priceN));
}
//for last occurence
var priceEls = document.getElementsByClassName("column--container value-item");
for (var i = 0; i < priceEls.length; i++) {
var price = priceEls[i].innerText;
//alert("Price: " + price);
var priceN = getNumber(price)*multiplier;
alert("Price: " + formatter.format(priceN));
}
function getNumber(myString) {
var numb = myString.match(/\d/g);
numb = numb.join("");
//alert (numb);
return(parseInt(numb));
}
<div class="price">$2,000</div>
<div class="price">
<span>$</span>
3,000
</div>
<div class="column--container value-item">
<span class="text-semibold-xs">Price</span>
$1,500
</div>
How do I update the HTML code with those new values?

One thing you can do after calculating the new prices is set the innerText of an element with the text you are using on the alert. So one of your loops can look like this
for (var i = 0; i < priceEls.length; i++) {
var price = priceEls[i].innerText;
var priceN = getNumber(price)*multiplier;
priceEls[i].innerText = "Price: " + formatter.format(priceN);
}
I would recomend using forEach for looping instead of for.

Related

Javascript CreateElement(br)

I am trying to create a score keeper display.
I want to keep track of the score using html and javascript. I have everything figured out I think but I can't figure out why the line doesn't break here.
Relevant code:
var br = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(br);
scorechart.appendChild(nc);
if(tot) {
scorechart.appendChild(br);
scorechart.appendChild(nes);
scorechart.appendChild(br);
scorechart.appendChild(tot);
}
(For a full view: https://hastebin.com/osuduluvaj.js)
It breaks for everything but the "------" part: https://media.discordapp.net/attachments/240883852350980096/497957073481629696/sAAAAASUVORK5CYII.png
(I cant upload images yet as a new member)
Thank you :)
document.createElement() creates a single element, which you can only append to the DOM once. If you want to reuse the <br> element you created, you need to clone it and you can insert the cloned copy into the DOM. See: Node.cloneNode().
var score = [];
var scoreadd_button = document.querySelector('#scoreadd-button');
var scoreadd_input = document.querySelector('#scoreadd-input');
let sc1 = 0;
let sc2 = 0;
var scorechart = document.querySelector('.scores');
function totalScores() {
var i;
var sum = 0;
for (i = 0; i < score.length; i++) {
sum += score[i];
}
return sum;
}
function newScore(amm) {
score.push(amm);
if (!score[1]) {
var nc = document.createTextNode(amm)
} else {
var nc = document.createTextNode(" + " + amm);
}
if (sc1 == 0) {
sc1 = amm;
} else {
sc2 = amm;
}
if (sc2 != 0) {
var tot = document.createTextNode("= " + totalScores());
sc1 = amm;
sc2 = 0;
}
var br = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(nc);
if (tot) {
scorechart.appendChild(br.cloneNode(true));
scorechart.appendChild(nes);
scorechart.appendChild(br.cloneNode(true));
scorechart.appendChild(tot);
}
}
scoreadd_button.addEventListener('click', function() {
var amm = scoreadd_input.value;
newScore(parseInt(amm, 10));
});
<button id="scoreadd-button">button</button>
<input type="text" id="scoreadd-input" />
<div class="scores"></div>
Okay so I fixed the issue by instead of using a variable just creating the element in the statement.
var nes = document.createTextNode("---------");
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(nc);
if(tot) {
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(nes);
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(tot);
}
Thank you :)
You just need to defined unique variables for each new created element on javascript, otherwise they will counted as one.
This code should works
var scorechart = document.querySelector('.scores');
var br = document.createElement("br");
var br2 = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(br);
scorechart.appendChild(nes);
scorechart.appendChild(br2);
<span class="scores">
text before
</span>
after text

Javascript combined value sliders

The solutions I have found are jQuery and can't understand them yet.
Anyways, I have a couple of sliders and I want to make it so that their combined max values are always less than a predefined value (variable called available in this case). So that when I change a slider, the max values of the other sliders change.
var available = 10;
var max = 0;
var old = 0;
window.onload = function () {
var sliders = document.getElementsByTagName("input");
var numSliders = sliders.length;
for (i = 0; i < numSliders; i++) {
//Define all sliders?
sliders.item(i).max = available;
document.getElementById(sliders.item(i).id + "val").innerHTML = sliders.item(i).value;
document.getElementById(sliders.item(i).id + "max").innerHTML = sliders.item(i).max;
sliders.item(i).addEventListener("input", function(){
updateSliders();
Slider(this);
})
}
}
function updateSliders() {
var sliders = document.getElementsByTagName("input");
var numSliders = sliders.length;
for (i = 0; i < numSliders; i++)
{
document.getElementById(sliders.item(i).id + "val").innerHTML = sliders.item(i).value;
document.getElementById(sliders.item(i).id + "max").innerHTML = sliders.item(i).max;
}
};
function Slider(active) {
//Get weird set thingy of all sliders
var sliderObject = document.getElementsByTagName("input");
var numberSliders = sliderObject.length;
var total = 0;
//Work out what is being displayed
for(i=0;i<numberSliders;i++)
{
var value = sliderObject.item(i).value;
total += parseInt(value);
}
for(i=0;i<numberSliders;i++)
{
var value = sliderObject.item(i).value;
max = available - value;
if(sliderObject.item(i) != active)
{
console.log("total = " + total);
console.log("old = " + old);
var difference = total - old;
console.log("Difference = " + difference);
sliderObject.item(i).max = sliderObject.item(i).max - (total - old);
}
}
old = total;
}
<div class="sliderContainer">
<input id="slider1" type="range" value=0> <span id="slider1val">0</span>/<span id="slider1max">0</span>
<br>
<input id="slider2" type="range" value=0> <span id="slider2val">0</span>/<span id="slider2max">0</span>
<br>
<input id="slider3" type="range" value=0> <span id="slider3val">0</span>/<span id="slider3max">0</span>
<br> </div>
It kinda works, but the numbers it displays are wrong or something?
Thanks for your time.
One thing you need to change is the order of function calls executed on input event. Slider(this) should be first.
Here is your fixed code: https://codepen.io/kejt/pen/xgoqeX

.innerHTML += id, no duplicates

Here what I have so I have a long list of check-boxes and I want to display them in text if they are check I was thinking of using the code below, but the problem I'm having is if they check and uncheck a check-box it shows up multiple times any suggestion on how to fix this?
.innerHTML += id;
If you need some more details here's a code dump of the relevant code:
Javascript
function findTotal() {
var items = new Array();
var itemCount = document.getElementsByClassName("items");
var total = 0;
var id = '';
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
if (document.getElementById(id).checked) {
total = total + parseInt(document.getElementById(id).value);
document.getElementById(id).parentNode.classList.add("active");
document.getElementById(id).parentNode.classList.remove("hover");
document.getElementById('display').innerHTML += id;
} else {
document.getElementById(id).parentNode.classList.remove("active");
document.getElementById(id).parentNode.classList.add("hover");
}
}
console.log(total);
document.getElementById('displayTotal').value = total;
}
HTML
<label class="hover topping" for="c4">
<input class="items" onclick="findTotal()" type="checkbox" name="topping" value="1.00" id="c4">BABYBEL</label>
Note: many more label classes
Previous answer should do it. Here your code (see comment "clear container"
Additionally I have simplified your code a bit. Readability greatly increased.
Maybe you should switch to jQuery in general, much simpler for your example.
var displayElement = document.getElementById('display'),
displayTotalElement = document.getElementById('displayTotal');
function findTotal() {
var items = [],
itemCount = document.getElementsByClassName("items"),
total = 0,
id = '';
// clear container
displayElement.innerHTML = "";
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
var element = document.getElementById(id),
elementsParent = element.parentNode;
if (element.checked) {
total = total + parseInt(element.value, 10);
elementsParent.classList.add("active");
elementsParent.classList.remove("hover");
displayElement.innerHTML += id;
} else {
elementsParent.classList.remove("active");
elementsParent.classList.add("hover");
}
}
console.log(total);
displayTotalElement.value = total;
}
Reset the text before the loop:
document.getElementById('display').innerHTML = '';
At the moment you're just always adding to whatever's already thereā€¦

Select random number from string of 1's and 0's and change color

I have a string of random 1's and 0's displayed via jQuery. I would now like to select a random number and change it's color. Is it better to work with an array, or a $(div).text() string? I can grab a number from either, but how do I insert it back into the div?
var numbArray = [];
for(i=0; i<10; i++)
{
var randomNumbers = Math.round(Math.random());
$('#numbs').prepend(randomNumbers);
numbArray[i] = randomNumbers;
}
<div id="numbs">0000110111 </div>
The div above is the result of the code, but how do I select a random item, change its color, and display in the original output?
Thanks,
You can locate the number at a certain index, wrap it with the desired color and rebuild the string and set it back to the div using html() and use Math.floor(Math.random() * 10) to generate the random number from zero to the length of the characters you have.
var index = 3;
var originalElementValue;
function colorStringValue(strIndex)
{
strIndex = parseInt(strIndex);
var character = originalElementValue.charAt(strIndex);
$("#numbs").html(originalElementValue.substr(0, strIndex) + "<span style='color:red'>" + character + "</span>" + originalElementValue.substr(strIndex+1));
}
$(document).ready(function(){
originalElementValue = $("#numbs").text();
colorStringValue(index);
$("#strIndex").click(function(){
var rand = Math.floor(Math.random() * 10) + 0 ;
$("#rand").html(rand);
colorStringValue(rand);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="strIndex" > Generate Random Number </button>
<br />
Random Number : <span id="rand"></span>
<br />
<div id="numbs">0000110111</div>
You need to pick a random index from the number string and append some element around that particular number to give it some style.
var number = '0000110111';
var index = Math.floor(Math.random() * number.length);
for(var i = 0; i < number.length; i++) {
var n = number.charAt(i);
if(i == index) {
$('#numbs').append($('<span/>').css('color', 'red').text(n));
} else {
$('#numbs').append(n);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="numbs"></div>
var numbArray = [];
for(i = 0; i< 10; i++) {
var randomNumbers = Math.round(Math.random());
numbArray[i] = randomNumbers;
$('#numbs').prepend(number);
}
var randomNumberSelection = numbArray[Math.floor((Math.random() * (numbArray.length-1)) + 1)];
$('#numbs').html("");
var number;
for(number in numbArray) {
if(number == randomNumberSelection) {
var colorColorCodedNumber = ""+number;
colorColorCodedNumber = colorColorCodedNumber.fontcolor("blue");//blue!
$('#numbs').prepend(colorColorCodedNumber);
} else {
$('#numbs').prepend(number);
}
}
I believe you're looking for something along the lines of this, or at least this is what I took from what you were asking.
In this example be aware you'll see we clear the element then simply reiterate over the array you stored earlier. That is how you 'update' it.
If I understand the question right you want to set a color for a specific position in the div. This means you have to create a span (or another html-element) inside the div at at a random position with a specific color. I havent tested this code below but I guess you could something like this: (in this example red color for the random item)
var randomIndex= Math.floor(Math.random() * 9); //Random number between 0 and 9.
var currentContent = $("#numbs").html();
var randomItem= currentContent.charAt(randomIndex);
newContent = '';
for(i=0; i<10; i++) {
if (i == randomIndex) {
newContent = newContent +
'<span style="background:red;">' + randomItem + '</span>';
}
else {
newContent = newContent + currentContent.charAt(i);
}
}
$("#numbs").html( newContent );
Is this what you are looking for? I just gave it a try. :)
var numbArray = [];
var sample = "<span style='color:#%COLOR%'>%NUM%</span>";
for(i=0; i<10; i++)
{
var randomNumbers = Math.round(Math.random());
var html = sample.replace('%NUM%', randomNumbers);
var randomColor = Math.round((Math.random()* 100000000 )%16777215).toString(16);
html = html.replace('%COLOR%', randomColor);
$('#numbs').prepend(html );
numbArray[i] = randomNumbers;
}
I assumed that you want random colors too.
Good answers by all; thanks! I didn't think of appending the DOM and redisplaying. I went with assigning each number an id and then using css without appending. I was looking for numbers that would turn a color and when all the numbers were that color the script would stop. I don't know which method would perform the best but this way is okay for my limited numbers.
var whiteNumbs =
[0,1,1,0,1,1,0,1,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,1,1,0,0,1,0]
for(var i=0; i<whiteNumbs.length; i++)
{
$("#numbs").append('<span class="white" id="num_' + i + '">' +
whiteNumbs[i] + '</span>');
}
function MakeRed()
{
var randomNumber = Math.floor(Math.random() * whiteNumbs.length-1);
var changeCSS = "#num_" + randomNumber;
$(changeCSS).removeClass('white');
$(changeCSS).addClass("red");
if ($("#numbs span").hasClass("white") )
{
setTimeout(MakeRed,1000);
}
else
{
return false;
}
};
MakeRed();

how to display the previous user input along with the new input

I am new to Html and I am trying to create a script to display user input back to the user.whenever i am entering a new input,the new user input over rides the previous input. but i need to display all the user inputs? how to do it using Javascript.
my code
<html><head></head><body>
<input id="title" type="text" >
<input type="submit" value="Save/Show" onclick="clearAndShow()" />
<div id="display2letter"></div>
<div id="display3letter"></div>
<div id="display4letter"></div>
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
function clearAndShow () {
// Split input box value by comma
titles = titleInput.value.split(",");
// Reset display divs
display2letter.innerHTML = "";
display3letter.innerHTML = "";
display4letter.innerHTML = "";
// Cache length so it's not recalculated on each iteration.
var len = titles.length;
var twoletter = [];
var threeletter = [];
var fourletter =[];
for (i = 0; i < len; i++) {
// Check for a-z, A-Z,
if (!titles[i].match(/^[a-zA-Z]/)) {
throw error("Please use only alphabet letters");
}
// Dump into storage arrays.
if(titles[i].length == 2) {
twoletter.push(titles[i]);
}
else if(titles[i].length == 3){
threeletter.push(titles[i]);
}
else if(titles[i].length == 4){
fourletter.push(titles[i]);
}
}
display2letter.innerHTML += " 2 letters: " + twoletter.join(", ") + "<br/>";
display3letter.innerHTML += " 3 letters: " + threeletter.join(", ") + "<br/>";
display4letter.innerHTML += " 4 letters: " + fourletter.join(", ") + "<br/>";
}
</script>
</body>
</html>
Try declaring these variables -
var twoletter = [];
var threeletter = [];
var fourletter =[];
before the clearAndShow () function, ie,
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
var twoletter = [];
var threeletter = [];
var fourletter =[];
function clearAndShow () {

Categories