I'm building a donate modal.
When I click on the donate button, the progress bar gets incremented based on the input value.
I want to replace the money string from h1 when I click on donate.
So if the input value is 10, when I click on the donate button the h1 should read:
$140 is still needed for this project
This runs only once, because it replaces the text only when it finds '$150'.
.modal
.modal-header-box
h1 $150 is still needed for this project
.modal-content
progress#myProgress(value='50', max='200')
h1 Only days left to fund this project. Join the other 42 other donors who have already suppoorted this project. Every dollar helps.
input(type='number', placeholder='$' id='value', max='100')
button#btn Give Now
.button.save-later Save for later
.button.social Tell your friends
JavaScript
document.getElementById('btn').addEventListener('click', function() {
var x = document.getElementById('myProgress');
console.log(x.value, document.getElementById('value').value)
x.value = +x.value + +document.getElementById('value').value;
let difference = x.max - x.value;
console.log(difference);
document.body.innerHTML = document.body.innerHTML.replace('$150', `${difference}`);
});
Is there any way to make this more dynamic, so the string will update If click on the donate button multiple times?
CodePen link
https://codepen.io/make96/pen/XWZdbPZ
Your problem resides in replacing everything on the page. You should restrict the transformation to the elements that you are changing.
Instead of replacing document.body, then target the modal header box instead.
document.body.innerHTML = document.body.innerHTML.replace('$150', `${difference}`);
Replace the modal-header-box content instead.
document.getElementsByClassName("modal-header-box")[0].innerHTML = `<h1>$${difference} is still needed for this project</h1>`;
Just put the number in a span and only change the span input on every click.
You take the value of the span and the value of the input box and substract it everytime you click on it.
Function:
document.getElementById("btn").onclick = function(){
var value = parseInt(document.getElementById("test").innerHTML);
var donate = parseInt(document.getElementById("value").value);
document.getElementById("myProgress").value += donate;
document.getElementById("test").innerHTML = value-donate;
}
modal-header-box
.modal-header-box
h1 $<span id="test">150</span> is still needed for this project
Don't replace the document body, Not good practice to update the body every time, update only the required field.
Javascript
document.getElementById("btn").addEventListener("click", function() {
const title = document.getElementById("title");
const x = document.getElementById("myProgress");
const prev = +x.value
x.value = prev + +document.getElementById("value").value;
let difference = x.max - x.value;
title.innerHTML = title.innerText.replace(x.max - prev, `${difference}`);
});
Template
h1#title $150 is still needed for this project
Related
I have this idea where if you press a button, it'll display a text, but not only one text, but multiple, just not at once. If you press the button again, it'll display another text after it. So far, I'm only limited to only one text being displayed. I'm not really sure how to go from what I'm trying to achieve. I had an idea about using arrays but arrays and buttons didn't seem to work all that great, at least for me. I might have done something wrong for it to not work. Anyways, the idea was that the button would call from the array each time you'd click it so it'd display a different text.
So if you press the button once, it would output: "Hello"
And if you press it again, it would output: "How are you?"
and so on and so forth.
How would I do this in terms of making something like this happen?
Disclaimer: I don't want the text to be replaced with a new text. I want it solely outputted afterwards.
<button id = "age-button" button onClick = "ageButton()">AGE!</button>
<script>
function ageButton() {
var text = "You are born.";
document.getElementById("age1").innerHTML = text;
}
</script>
This code above only displays one text. How would I let it display another text after I press the button again?
// Define array of string that you would like to show on each click
const labels = [
"String 1",
"String 2",
"String 3"
// ... so on (add as many as you like)
];
// lets start from zero index
let currentIndex = 0;
// get the button HTMLElement
const nextBtn = document.querySelector("#next-btn");
const contentsEl = document.querySelector("#contents");
// attach onClick event handler / listner
nextBtn.addEventListener("click", function(event) {
// get the label string to show
const label = labels[currentIndex];
const p = document.createElement("p");
p.textContent = label;
contentsEl.append(p);
// increment the index
currentIndex++;
// set a trap
if (currentIndex === labels.length) {
//(bonus) disable the button when you reach the end
this.disabled = true;
}
});
<button id="next-btn">Show Next</button>
<div id="contents"></div>
Here is an example how you can do that.
let texts = ["You are born", "Hi there", "I'm ready"];
function ageButton() {
let line = texts.shift(); //use shift to get the first element in array
if (line) {
//use += operator to append to previous content
document.getElementById("age1").innerHTML += "<p>" + line + "</p>";
}
}
<button id="age-button" onclick="ageButton()">AGE!</button>
<div id="age1"></div>
When the user visits the page, this HTML text must display.
<p id="exampleText">Hit The "Change Text" Button Below To Change <span id="thisText"><strong>This</strong></span> Text and see how the innerHTML property tag works </p>
After clicking this button:
<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>
Display This Text:
var txtExmp1 = "Hooooooooooooraayy!!, You Clicked and Changed The Text..." + "<br><br><br>" + "but now you have to fix me so i can change again";
Now user should be able to click the button and see previous text and back to the "Hooray" message in var txtExmp1.
I've tried to use an if statement but didnt work. Here's the code:
var defaultText = document.getElementById("exampleText");
if (defaultTex.innerHTML === defaultText){
defaultText.innerHTML = txtExmp1;
}
else {
defaultText.innerHTML = defaultText;
}
How can I make this texts toggle between each other considering one is html and the other is javascript. What is the simple and most effective way to toggle this texts?
Heres what it looks like (Screenshot image):
i.Before Click
ii.After click, but wont change again
This is relatively simple, when changing the text you need to take the current visible one and save it in a variable, then show the other stored text you have in txtExmp1 then when the use click again you take the other visible text store it and show the one you stored before, doing it this is highly inefficient.
From the start you store both strings in variables or array then toggle between them.
Of course this is just one way to achieve this.
let text = ["Hooooooooooooraayy!!, You Clicked and Changed The Text... <br><br><br>but now you have to fix me so i can change again", "Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works "];
let index = 0;
function textChanger() {
// Get the p Element refrence so we can modify it
var pElement = document.getElementById("exampleText");
// text[index] will return one of the texts from the array
// depening on the index if 0 its the first one
// if 1 it's the second one
// that's why we're altering index's value after every change
if (index == 0) {
pElement.innerHTML = text[index];
index = 1;
} else if (index == 1) {
pElement.innerHTML = text[index];
index = 0;
}
}
<p id="exampleText">Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works </p>
<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>
The word you are searching is toggle. Try switch case:
var theToggle = document.getElementById("changeButton");
var toggleMe = document.getElementById("exampleText");
toggleMe.toggleStatus = "on";
theToggle.onclick = function(){
switch(toggleMe.toggleStatus){
case "on":
toggleMe.toggleStatus="off";
toggleMe.textContent = "Hooooooooooooraayy";
break;
case "off":
toggleMe.toggleStatus="on";
toggleMe.textContent = " Hit The Change Text Button Below To change...";
break;
}
Good luck!
Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone
Here i'm trying to calculate the values based upon the active span. I've posted my full codes on jsfiddle. Span is not contenteditable. And another important thing is i'm assuming span values are 40. So, if user selected the span it would change into green color. if user click another span span#returndata should be 40+40 = 80. if user clicks another span the result should be 40+40+40 = 120.
I've tried below jquery. But i didn't get the result..
JsFiddle
jQuery
$(".text").click(function(){
$(this).toggleClass('selected');
$(function(){
$('span#text').click(function(){
value = 40;
var t = ('span#text').value;
var total = (t+t);
$('span#returndata').val(total);
});
});
});
I updated your jFiddle to make it work. http://jsfiddle.net/m89L4/6/
It is better to recalculate the value everytime a user clicks based upon the number of seats chosen because you may get inconsistencies otherwise.
JS Code
$(".text").click(function(){
$(this).toggleClass('selected');
var count = $('.selected').length;
var value = 40;
$('.returndata').text(value*count);
});
Try this one
$(".text").click(function(){
$(this).toggleClass('selected');
value = 40;
var t = parseInt($(this).text(),10);
var total = parseInt(value+t);
$('span.returndata').text(total);
})
is there a way to change the text inside a div using a link, but to keep changing it every time the link is clicked? I tried innerhtml and I can get it to change once, but after it is changed how to change yet again to new text. The end result is every time the "next" link is clicked new text loads? I do not have any code to start from so any help would be great
I'm not really sure you want the text to be, but you should be able to customize this to make it work no matter where you're getting the text from:
(function(){
var texts = [
'This is the first message',
'This is the second message',
'This is the last message'
], i = 0;
document.getElementById('text').innerHTML = texts[0];
document.getElementById('left').onclick = function(){
if(i <= 0)
i += 3;
document.getElementById('text').innerHTML = texts[--i%texts.length];
}
document.getElementById('right').onclick = function(){
document.getElementById('text').innerHTML = texts[++i%texts.length];
}
})();
http://jsfiddle.net/YDA7v/