How to display the value of my button in a paragraph - javascript

I'm trying to figure out how to display the value of my button in a paragraph. I feel like this is super simple and I'm just doing something dumb.
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<button type="button" class="btn btn-dark" id="0" onclick="Add2list" value="BarBell Bench Press" >BarBell Bench Press</button>
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>
function Add2list() {
var x= document.getElementById("0")
document.getElementById("Workouts2do").innerHTML = x;
}

Add2list is a function, so onclick="Add2list()" and you want the value of the button so var x = document.getElementById("0").value
function Add2list() {
var x = document.getElementById("0").value
document.getElementById("Workouts2do").innerHTML = x;
}
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<button type="button" class="btn btn-dark" id="0" onclick="Add2list()" value="BarBell Bench Press">BarBell Bench Press</button>
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>

You haven't added which attribute you want to get from the button. Also, you can't directly add the whole reference.
Just mention which attribute you want to take from the button
You haven't called the function when passed to onclick attribute
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<button type="button" class="btn btn-dark" id="0" onclick="Add2list()" value="BarBell Bench Press" >BarBell Bench Press</button>
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>
function Add2list() {
var x= document.getElementById("0").value
document.getElementById("Workouts2do").innerHTML = x;
}

OnClick needs a function always
You need to specify what you are going to get from the button
option 1:
var x = document.getElementById("0").value
document.getElementById("Workouts2do").innerHTML = x;
option 2:
var x = document.getElementById("0")
document.getElementById("Workouts2do").innerHTML = x.value;
if you want to have a list and not clear it every time you need to click on the button you could use +=
For new line since it's inner HTML you can use only.
function Add2list() {
var x = document.getElementById("0")
document.getElementById("Workouts2do").innerHTML += x.value + `<br>`;
}
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<button type="button" class="btn btn-dark" id="0" onclick="Add2list()" value="BarBell Bench Press">BarBell Bench
Press</button>
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>

You should probably change your button to "input" but leave it's type at "button". Also, var is no longer used, you should use "let" as so:
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<input type="button" class="btn btn-dark" id="0" value="BarBell Bench Press" />
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>
the js:
document.getElementById("0").addEventListener("click", Add2list);
function Add2list() {
// Selecting the input and get value
let inputVal = document.getElementById("0").value;
// output the value
document.getElementById("Workouts2do").innerHTML = inputVal;
}

Related

Problem showing questions in a quiz made in javascript

I have a form with 5 questions, in which they are displayed one at a time to the user, as in a quiz, that is, the first question appears on the screen, the user answers and goes to the second, and so on.
However, I have a problem with questions 3 and 4, when I don't type anything and press ENTER, question 2 is also appearing on the screen, like the image below:
[![error in questions 3 and 4][1]][1]
[1]: https://i.stack.imgur.com/63pQC.png
I can't show two questions at the same time, just one at a time, and I don't know where I'm going wrong.
Here's the code inside the form tag:
<form class="questions_box formulario" action="enviar-landing-page-v3.php" method="post">
<div id="question-1">
<h3>The question is: ... ?</h3>
<input type="radio" name="objetivo" id="question-1-answer-a" value=1 required oninput="checkObjective()"> Answer 1.<br>
<input type="radio" name="objetivo" id="question-1-answer-b" value=2 oninput="checkObjective()"> Answer 2.<br>
<input type="radio" name="objetivo" id="question-1-answer-c" value=3 oninput="checkObjective()"> Answer 3.<br>
<div class="text-end mt-3">
<input type="submit" id="submit1" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<script type="text/javascript">
function checkObjective() {
if (document.getElementsByName('objetivo').value == '') {
document.getElementById('submit1').style.display = 'none';
} else {
document.getElementById('submit1').style.display = 'block';
}
}
</script>
</div>
<div id="question-2">
<h3>Quantos anos tem seu filho(a)?</h3>
<div class="input-formulario">
<i class="far fa-calendar-alt"></i>
<input required type="text" name="idade_aluno_lp" id="idade_aluno_lp" placeholder="Digite a idade do aluno" oninput="checkAge()" maxlength="2" />
</div>
<div class="text-center mt-3">
<input type="submit" id="submit2" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous2" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkAge() {
var countAge = document.getElementById('idade_aluno_lp');
countAge.value = countAge.value.replace(/\D/, ''); // Remove caracteres que não sejam números
if (countAge.value.length == 0) { // 0 caracteres digitados
document.getElementById('submit2').style.display = 'none';
} else {
document.getElementById('submit2').style.display = 'block';
}
}
</script>
</div>
<div id="question-3">
<h3>Qual seu nome?</h3>
<div class="input-formulario">
<i class="far fa-user"></i>
<input required type="text" name="nome_lp" id="nome_lp" placeholder="Digite seu nome" oninput="checkName()">
<span id="error-name"></span>
</div>
<div class="text-center mt-3">
<input type="submit" id="submit3" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-center mt-3">
<input type="submit" id="previous3" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkName() {
var countName = document.getElementById('nome_lp');
var errorName = document.getElementById('error-name')
countName.value = countName.value.replace(/[0-9]/g, ''); // Remove numbers
if (countName.value.length < 3) { // 0 chars entered
errorName.innerHTML = "O nome precisa ter ao menos 3 caracteres."
document.getElementById('submit3').style.display = 'none';
} else {
errorName.innerHTML = "";
document.getElementById('submit3').style.display = 'block';
}
}
</script>
</div>
<div id="question-4">
<h3>Qual seu email?</h3>
<div class="input-formulario">
<i class="fas fa-at"></i>
<input required type="email" name="email_lp" id="email_lp" placeholder="Digite seu email" oninput="checkEmail()">
<span id="error-email"></span>
</div>
<div class="text-center mt-3">
<input type="submit" id="submit4" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous4" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkEmail() {
var email = document.getElementById('email_lp');
var errorEmail = document.getElementById('error-email');
if (!email.checkValidity()) {
errorEmail.innerHTML = "O email deverá seguir o padrão: meuemail#provedor.com";
document.getElementById('submit4').style.display = 'none';
} else {
errorEmail.innerHTML = "";
document.getElementById('submit4').style.display = 'block';
}
}
</script>
</div>
<div id="question-5">
<h3>Qual seu whatsapp?</h3>
<div class="input-formulario">
<i class="fab fa-whatsapp"></i>
<input required type="text" name="celular_lp" id="celular_lp" placeholder="Digite seu DDD + celular" maxlength="14" onkeypress="return mascaraCelular(event)" oninput="checkMobile()">
<span id="error-mobile"></span>
</div>
<div class="text-end mt-3">
<input type="submit" id="submit5" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous5" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
</div>
<script type="text/javascript">
function checkMobile() {
var countMobile = document.getElementById('celular_lp');
var errorMobile = document.getElementById('error-mobile');
if (countMobile.value.length < 13) {
errorMobile.innerHTML = "Além do DDD, o número do celular precisa ter ao menos 8 dígitos";
document.getElementById('submit5').style.display = 'none';
} else {
errorMobile.innerHTML = "";
document.getElementById('submit5').style.display = 'block';
}
}
</script>
</form>
And the javascript responsible for show/hide the questions:
// Variables
var submit1 = document.getElementById('submit1');
var submit2 = document.getElementById('submit2');
var submit3 = document.getElementById('submit3');
var submit4 = document.getElementById('submit4');
var previous2 = document.getElementById('previous2');
var previous3 = document.getElementById('previous3');
var previous4 = document.getElementById('previous4');
var previous5 = document.getElementById('previous5');
// Next question button
submit1.addEventListener('click', function() {
nextQuestion(2);
growProgressBar('40%');
})
submit2.addEventListener('click', function() {
nextQuestion(3);
growProgressBar('60%');
})
submit3.addEventListener('click', function() {
nextQuestion(4);
growProgressBar('80%');
})
submit4.addEventListener('click', function() {
nextQuestion(5);
growProgressBar('100%');
})
// grow Progress Bar
function growProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows next question, hides current
function nextQuestion(question_number) {
var current_question_number = question_number - 1; //question_number is the next question
var question_number = question_number.toString();
var current_question_number = current_question_number.toString();
document.getElementById('question-' + question_number).style.display = 'block';
document.getElementById('question-' + current_question_number).style.display = 'none';
}
// Previous question button
previous2.addEventListener('click', function() {
previousQuestion(1);
shrinkProgressBar('20%');
})
previous3.addEventListener('click', function() {
previousQuestion(2);
shrinkProgressBar('40%');
})
previous4.addEventListener('click', function() {
previousQuestion(3);
shrinkProgressBar('60%');
})
previous5.addEventListener('click', function() {
previousQuestion(4);
shrinkProgressBar('80%');
})
// Shrink Progress Bar
function shrinkProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows previous question, hides current
function previousQuestion(question_number) {
var current_question_number = question_number + 1;
var question_number = question_number.toString();
var current_question_number = current_question_number.toString();
var el = document.getElementById('question-' + question_number);
console.log(question_number);
var el2 = document.getElementById('question-' + current_question_number);
el.style.display = 'block';
el2.style.display = 'none';
}
About Carsten Massmann answer:
The problem with the code was just to change the buttons type="submit" to type="button", and leave only the last button as type="submit", however, I really liked your code, I learned a lot, for example, I had never read about closest method. Could you explain to me how these two lines of code work (what they are for I understand):
current = (Q.length + current + inc) % Q.length; // cycle through questions...
Above I don't understand why you use the question length.
And on the next line, I don't understand why I use trim():
(el.value.trim() ? "block" : "none")
I also understand that you cycle between questions, but I need to demarcate the first and last question in the loop, and put something like if Q=0, don't show the "Previous question" button, and if Q=4, that the final button would execute method="POST" and action="next-page". I believe that the "submit" is not being executed because of the loop, but I don't understand why the loop takes precedence over the submit.
The following snippet is still missing your actual validation functions for individual fields but I hope it illustrates the point of how you can avoid unnecessary repetitions in your code and markup. I am using classes to address the various input elements and "delegated event attachment" to combine the click handling for different buttons. For simplicity I allow cycling through the questions. Feel free to change and adapt ...
function changeQ(inc){
current= (Q.length+current+inc)%Q.length; // cycle through questions ...
Q.forEach((q,i)=>q.style.display=(i==current?"":"none"))
}
function showHideOK(el){
let ok=!!el.value.trim();
el.closest(".input-formulario").querySelector("input.ok").style.display=
(ok?"block":"none");
ans[el.name]=ok;
}
document.querySelectorAll("div.input-formulario").forEach((div,i)=>{div.innerHTML+=`<div class="text-end mt-3"><input type="submit" class="btn btn-primary btn-lg back" value="Pergunta Anterior"/></div><div class="text-center mt-3"><input type="submit" class="btn btn-primary btn-lg ok" value="Próxima Pergunta"/></div>`;
div.addEventListener("input",ev=>{ let el=ev.target;
if (el.tagName!=="INPUT") return // only act on input elements ...
showHideOK(el)
btn.style.display=Object.values(ans).filter(a=>a).length==Q.length?"":"none";
});
div.onclick=ev=>{if (ev.target.type=="submit") {
ev.preventDefault();
changeQ( ev.target.classList.contains("back")?-1:1 );
}}
})
const btn = document.querySelector("button"),
Q=document.querySelectorAll(".question"),
ans={};
let current=0;
changeQ(0);
btn.style.display="none";
input.ok {display:none}
<form class="questions_box formulario" action="enviar-landing-page-v3.php" method="post">
<div class="question">
<div class="input-formulario">
<h3>The question is: ... ?</h3>
<label><input type="radio" name="objetivo" value=1 required> Answer 1.</label><br>
<label><input type="radio" name="objetivo" value=2> Answer 2.</label><br>
<label><input type="radio" name="objetivo" value=3> Answer 3.</label><br>
</div>
</div>
<div class="question">
<h3>Quantos anos tem seu filho(a)?</h3>
<div class="input-formulario">
<input required type="number" name="idade_aluno_lp" placeholder="Digite a idade do aluno" maxlength="2" />
</div>
</div>
<div class="question">
<h3>Qual seu nome?</h3>
<div class="input-formulario">
<input required type="text" name="nome_lp" placeholder="Digite seu nome"> <span></span>
</div>
</div>
<div class="question">
<h3>Qual seu email?</h3>
<div class="input-formulario">
<input required type="email" name="email_lp" id="email_lp" placeholder="Digite seu email"> <span></span>
</div>
</div>
<div class="question">
<h3>Qual seu whatsapp?</h3>
<div class="input-formulario">
<input required type="text" name="celular_lp" id="celular_lp" placeholder="Digite seu DDD + celular"
maxlength="14"> <span></span>
</div>
</div>
<br><button>Enviar todas as respostas</button>
</form>
Further explanations:
Why am I using Q.length?
The expression current = (Q.length + current + inc)/Q.length uses Q.length (=total number of questions) to keep current always within the range of existing question indexes. The term Q length+... is necessary to keep values positive for the situation where current=0 and inc=-1 and % Q.length limits the results from 0 to Q.length-1.
Why do I use .trim()?
This is just a simple way of avoiding that an answer containing only blanks would be accepted as a valid answer.
Why is there no "submit"?
I actively disabled the submit action by calling ev.preventDefault() within my event-handling function.
How to submit the answers, and when?
There are many different ways of doing it. My suggestion would be to keep cycling through the questions until all questions are answered in a valid way. At that point an extra button appears that submits all answers at once. I just added that button (btn) to the script. It is hidden at first through btn.style.display="none" but made visible again on the condition that all questions have received an answer:
btn.style.display=Object.values(ans).filter(a=>a).length==Q.length?"":"none";
The (global) object ans is constantly updated in the function showHideOK():
let ok=!!el.value.trim();
...
ans[el.name]=ok;

How to create a reply button that displays for each button clicked one at a time

I'm creating a comment and reply system, but I can't get the reply button to display the input field for only the comment.
When the any reply button is clicked, all the input fields displays instead of just the one clicked
This is my javascript:
function reply() {
var doc;
doc=document.getElementsByClassName("sho") ;
for (var i = 0 ; i < doc.length; i++){
doc[i].style.display="block ";
}
}
$('.btn-reply').on("click", function () {
var parent_dom = $(this).parent();
var _input_child_dom = $(parent_dom).children("input");
var find_allInput = $('.reply-container').find("input");
if(find_allInput.length > 0 ){
for (var i = 0; i < find_allInput.length; i++) {
$(find_allInput[i]).css("display" , "none");
}
}
$(_input_child_dom).css("display" , "block");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="reply-container">
<div class="reply">
<p>First reply</p>
<button class="btn btn-primary btn-reply">reply</button>
<input type="text" class="InputReply" style="display: none;">
</div>
<br>
<div class="reply">
<p>Second reply</p>
<button class="btn btn-primary btn-reply">reply</button>
<input type="text" class="InputReply" style="display: none;">
</div>
<br>
<div class="reply">
<p>Third reply</p>
<button class="btn btn-primary btn-reply">reply</button>
<input type="text" class="InputReply" style="display: none;">
</div>
</div>
Note: This is the idea of how you can achieve your requirement.

jQuery multiple plus/minus Counter

I want to have multiple plus/minus counters on my page.
I have one working counter but want to make it generic so that multiple counters can have a different initial value and increase and decrease as clicked.
$('.counter-btn').click(function(e) {
e.preventDefault();
var $btn = $(this);
$('.output').html(function(i, val) {
val = val * 1 + $btn.data('inc');
return (val <= 0 ? '' : '+') + val;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>
<hr />
<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>
Fiddle Link:
http://jsfiddle.net/u2Lh7dbp/
Thanks
Each output element should be unique so it can be called by itself.
$('.counter-btn').click(function(e) {
e.preventDefault();
var $btn = $(this);
$('#output-' + $btn.data('index')).html(function(i, val) {
val = val * 1 + $btn.data('inc');
return (val <= 0 ? '' : '+') + val;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-index="1" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-index="1" data-inc="-1">-</button>
<div class="output" id="output-1">+30</div>
<hr />
<button class="counter-btn" id="increase2" type="button" data-index="2" data-inc="1">+</button>
<button class="counter-btn" id="decrease2" type="button" data-index="2" data-inc="-1">-</button>
<div class="output" id="output-2">+30</div>
I've added a new data attribute: index. You can use that index to specify the exact output element you're looking for by its id.
Keeping it simple, you can have two functions and directly associate the onClick callback to these functions, making it more clear on the html side.
function add(id) {
var newCount = parseInt($(id).text()) + 1;
$(id).text(newCount);
}
function substract(id) {
var newCount = parseInt($(id).text()) - 1;
$(id).text(newCount);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="add('#output1')">+</button>
<button type="button" onclick="substract('#output1')">-</button>
<div id="output1">30</div>
<hr />
<button type="button" onclick="add('#output2')">+</button>
<button type="button" onclick="substract('#output2')">-</button>
<div id="output2">30</div>

Function to check total value

I want to check the total value in the calculator so that i can show an answer as a chemical formula for example after pressing O which has value of "9" and adding C with value of "8" i would get 17 and i want to make a function that would detect the value and say something in these lines: "You've created CO2"
I just want some directions or a pointer because i really want to learn and i'm still a newbie anyway here's the calculator:
$(document).ready(function(){
var inputs=[""];
var totalString;
var operator1 = ["+"];
var operator2 = ["."];
var nums=[0,1,2,3,4,5,6,7,8,9];
function getValue(input){
if(inputs.length===1 && operator1.includes(input)===false){
inputs.push(input);
}
else if(operator1.includes(inputs[inputs.length-1])===false){
inputs.push(input);
}
else if(nums.includes(Number(input))){
inputs.push(input);
}
update();
}
function update(){
totalString= inputs.join("");
$("#steps").html(totalString);
}
function getTotal(){
totalString= inputs.join("");
console.log(totalString + ": " + eval(totalString));
$("#steps").html(eval(totalString));
}
$("a").on("click",function(){
if(this.id==="deleteAll"){
inputs = [""];
update();
}
else if(this.id==="backOne"){
inputs.pop();
update();
}
else if(this.id==="total"){
getTotal();
}
else{
if(inputs[inputs.length-1].indexOf("+")===-1){
getValue(this.id);
}
else {
getValue(this.id);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-center">
</div>
<div id ="calcOutput">
<span id= "steps"></span>
<hr/>
</div>
<div class="text-center"
id="calculator">
<a class="btn btn-danger"
id="deleteAll">AC</a>
<a class="btn btn-danger"
id="backOne">CE</a>
<br/>
<a class="btn btn-primary"
value="7"
id="7">H</a>
<a class="btn btn-primary"
value="8"
id="8">O</a>
<a class="btn btn-primary"
value="9"
id="9">C</a>
<br/>
<a class="btn btn-primary"
value="4"
id="4">N</a>
<a class="btn btn-primary"
value="5"
id="5">F</a>
<a class="btn btn-primary"
value="6"
id="6">S</a>
<br/>
<a class="btn btn-primary"
value="1"
id="1">Fe</a>
<a class="btn btn-primary"
value="2"
id="2">Na</a>
<a class="btn btn-primary"
value="3"
id="3">Cl</a>
<br/>
<a class ="btn btn-primary bigButton" id="total">=</a>
<a class ="btn btn-primary bigButton" id="+">+</a>
</div>
Thank you for any help, and every other comments!
I am not sure I understand the approach.
Are you trying to map 17 to CO2 ? If that is the case then there could be number of ways to produce 17, like FE+O+O = (1+8+8)= 17, that may not be the result you are expecting. I would say to maintain an array(map) of compounds like co2,o2 etc.
And then append the text instead of adding number while keypress.
Eg: user press C + O, then check in the array with all compounds having CO.

jQuery to get HTML value and find and replace $ or £ in content

Im a little new to JS / jQuery and this site is on shopify so i cant do much with functionality so trying to work around with JS but i need to grab the values, strip the currency then add them together and re-display but this is as far as ive got but not working...
Any ideas?
setTimeout(function() {
var a = $(".cart-total span").html().replaceText(/$|£/gi, "");
var b = $("#estimated-shipping em").html().replaceText(/$|£/gi, "");
var total = a + b;
$('.cart-finalTotal span').html("£" + total);
console.log(total);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="cart-right">
<p class="cart-total">Sub-Total<span class="money">£249.00</span>
</p>
<p class="cart-vat">VAT 20% (included)<span class="money">£49.80</span>
</p>
<p class="cart-delivery">Delivery<span class="money" id="estimated-shipping">+ <em>$9.00</em></span>
</p>
<p class="cart-finalTotal">Total<span class="money">£249.00</span>
</p>
<div class="cart-checkout">
<button class="button button-primary button-add-to-cart button-pay-now" type="submit" name="checkout"><span class="icom-lock"></span>Pay Now</button>
<br>
<br>
<div class="additional-checkout-buttons">
<p>Or checkout with</p>
<img id="applePayButton" style="display: none" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" onload="typeof createApplyPayButton === 'function' ? createApplyPayButton(this) : window.addEventListener('applePayReady', (function(){createApplyPayButton(this)}).bind(this))">
<input type="image" name="goto_pp" value="paypal_express" src="https://www.paypalobjects.com/en_US/i/btn/btn_xpressCheckout.gif">
</div>
</div>
</div>
Escape your regular expression $ with a backslash.
Replace text is not a jquery function just use text().replace(/\$|£/gi, '')
Also convert those strings into numbers by using parseFloat(a, 10)
Here is the working example, however you are adding dollar and pound here which seems to be wrong.
setTimeout(function() {
var a = parseFloat($(".cart-total span").text().replace(/\$|£/gi, ""));
var b = parseFloat($("#estimated-shipping em").text().replace(/\$|£/gi, ""));
var total = a + b;
$('.cart-finalTotal span').html("£" + total.toFixed(2));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cart-right">
<p class="cart-total">Sub-Total<span class="money">£249.00</span>
</p>
<p class="cart-vat">VAT 20% (included)<span class="money">£49.80</span>
</p>
<p class="cart-delivery">Delivery<span class="money" id="estimated-shipping">+ <em>$9.00</em></span>
</p>
<p class="cart-finalTotal">Total<span class="money">£249.00</span>
</p>
<div class="cart-checkout">
<button class="button button-primary button-add-to-cart button-pay-now" type="submit" name="checkout"><span class="icom-lock"></span>Pay Now</button>
<br>
<br>
<div class="additional-checkout-buttons">
<p>Or checkout with</p>
<img id="applePayButton" style="display: none" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" onload="typeof createApplyPayButton === 'function' ? createApplyPayButton(this) : window.addEventListener('applePayReady', (function(){createApplyPayButton(this)}).bind(this))">
<input type="image" name="goto_pp" value="paypal_express" src="https://www.paypalobjects.com/en_US/i/btn/btn_xpressCheckout.gif">
</div>
</div>
</div>
My proposal is:
instead to escape you can use the format [$£] in regex
round numbers after adding them
use replace instead of replaceText
use text instead of html to set the result into the span
$(function () {
setTimeout(function() {
var a = $(".cart-total span").html().replace(/[$£]/gi, "");
var b = $("#estimated-shipping em").html().replace(/[$£]/gi, "");
var total = parseFloat(a) + parseFloat(b);
total = parseFloat(Math.round(total * 100) / 100).toFixed(2);
$('.cart-finalTotal span').text("£" + total);
console.log(total);
}, 1000);
});
<script src="http://code.jquery.com/jquery-1.12.1.min.js"></script>
<div class="cart-right">
<p class="cart-total">Sub-Total<span class="money">£249.00</span>
</p>
<p class="cart-vat">VAT 20% (included)<span class="money">£49.80</span>
</p>
<p class="cart-delivery">Delivery<span class="money" id="estimated-shipping">+ <em>$9.00</em></span>
</p>
<p class="cart-finalTotal">Total<span class="money">£249.00</span>
</p>
<div class="cart-checkout">
<button class="button button-primary button-add-to-cart button-pay-now" type="submit" name="checkout"><span class="icom-lock"></span>Pay Now</button>
<br>
<br>
<div class="additional-checkout-buttons">
<p>Or checkout with</p>
<img id="applePayButton" style="display: none" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" onload="typeof createApplyPayButton === 'function' ? createApplyPayButton(this) : window.addEventListener('applePayReady', (function(){createApplyPayButton(this)}).bind(this))">
<input type="image" name="goto_pp" value="paypal_express" src="https://www.paypalobjects.com/en_US/i/btn/btn_xpressCheckout.gif">
</div>
</div>
</div>

Categories

Resources