Create anchor text inside .innerhtml javascript function - javascript

I have a subscription form where user selects service and number of hours. Onsubmit I call a function which displays the result/total price. The function looks like this:
<script type="text/javascript">
function calc()
{
var total = 0;
var course = 0;
var nrOfLessons = 0;
var vat = 0;
course = Number(document.getElementById("course").value)
nrOfLessons = Number(document.getElementById("nrOfLessons").value)
total =(course * nrOfLessons)
vat = total * 0.15
total = total+ vat;
document.getElementById("result").innerHTML = "The total is "+total+" Click here to Pay
}
</script>
Now my question is this. How can I change the text from above "click here to pay" into a link. I tried everything that I can think off but I am stumped.
Thanxs in advance for all the help. Please try to keep answers newbie friendly :-)

You can turn that into a link by using:
document.getElementById("result").innerHTML =
"The total is "+total+" <a href='[url-here]'>Click here to Pay</a>";
Replace [url-here] with the URL of your payment page.

Related

Can I set a function to use different variables depending on how it’s triggered?

I’m making a page to track the quantity/value of 8 sets of assets.
Each Asset will have several buttons that do the same thing just for different Variables depending on the asset that triggers them.
I’m wondering if there is a way to set the variables when it’s triggered or do O just have to copy-paste and edit each function 8 times?
Here is the code I’m starting with it adds A quantity of the asset and removes the cost from the cash value
function buya() {
var quant = document.getElementById("input").value;
quant = Number(quant)
var cost = document.getElementById("a3").innerHTML;
var cash = document.getElementById("cash").innerHTML;
cash = Number(cash)
cost = Number(cost)
var a4 = document.getElementById("a4").innerHTML;
a4 = Number(a4)
console.log(a4)
console.log(quant)
if (cash > cost) {
cash = cash - cost;
a4 += quant;
document.getElementById("cash").innerHTML = cash;
document.getElementById("a4").innerHTML = a4;
} else
alert("you don't have enough money to buy those shares")
}
Basically I want to swap most all of the variables a3, a4 into b2,b4 variables
——edit—— Okay I think I have a fix but it’s clumsy and better ones would be appreciated.
First Add a drop-down to select which asset then replace the things I want to shift with blank variables m, say cuz then at the start of the function add an 8 pronged if/else statement assigning field locations to those variables based on the drop-down selection.
Hate it when the answer pops into my head 5 minutes after posting
——edit ends——
Use function parameters, and then bind event listeners to functions that call it with different parameters.
function buya(costid, a4id) {
var quant = document.getElementById("input").value;
quant = Number(quant)
var cost = document.getElementById(costid).innerHTML;
var cash = document.getElementById("cash").innerHTML;
cash = Number(cash)
cost = Number(cost)
var a4 = document.getElementById(a4id).innerHTML;
a4 = Number(a4)
console.log(a4)
console.log(quant)
if (cash > cost) {
cash = cash - cost;
a4 += quant;
document.getElementById("cash").innerHTML = cash;
document.getElementById(a4id).innerHTML = a4;
} else
alert("you don't have enough money to buy those shares")
}
someElement.addEventListener("click", () => buya("a3", "a4"));
otherElement.addEventListener("click", () => buya("b2", "b4"));
We can pass elements as parameters to the function
function buya(ele1, ele2){
console.log(ele1.innerHTML);
console.log(ele2.innerHTML);
}
<div id="a3">I am a3</div>
<div id="a4">I am a4</div>
<div id="b3">I am b3</div>
<div id="b4">I am b4</div>
<button onClick="buya(document.getElementById('a3'), document.getElementById('a4'));">Click for A3 and A4</button>
<button onClick="buya(document.getElementById('b3'), document.getElementById('b4'));">Click for B3, B4</button>

How to add value of variable at the end of URL in JavaScript?

I have a counter button which increases the number when clicked.
Also I have an URL like http://localhost:5000/x/.
What I want is:
Printing the counter value at the end of the URL.
For example:
If counter=3, I want to go http://localhost:5000/x/3;
My button type is submit and it increases the value of counter and goes the pagehttp://localhost:5000/x/counter. However, I got 404 Error because the data is on the http://localhost:5000/x/3. Here is the code.
<form action="http://localhost:5000/x/counter">
<script>
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
Thanks.Additional I don't use any framework and I want to handle it just by using JavaScript.
EDIT:
Thanks for your answers. I solved it by using window.location.href function.
Retrieve counter using url of page
var counter = location.href.substring(location.href.lastIndexOf('/')+1);
counter = parseInt(counter);
counter += 1;
Set myform action using counter
document.myform.action = location.href.substring(0,location.href.lastIndexOf('/'))+counter;
Name your form
<form name='myform'>

how do i output a variable from js for html

Please I want to output a variable from js to an html tag so i can see the results in a specific place on my page. here is the code:
<script type="text/javascript">
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById("my_input3").value;
var my_input4 = document.getElementById("my_input4").value;
//alert(form.elements["my_input2"].value);
//var my_input3 = document.getElementById('my_input3').value;
// Add them together and display
var sum = parseInt(my_input1) / parseInt(my_input2) * parseInt(my_input3) * parseInt(my_input4);
document.write(sum);
}
Let us say you want to display the response in a div with id sum
<div id="sum"></div>
To do so, update
document.write(sum);
to
document.getElementById("sum").innerHTML = sum;

Why is JavaScript correctly calculating my variable yet displays it as undefined in the HTML?

And how do I get it to display the number, not undefined?
It's a tipping app. The user inputs the price of whatever it is they bought (pizza, haircut, etc.) in #price, then calcTip() calculates the tip, sends it over to calcTotal() which calculates the total, and sends it over to displayAmounts().
I don't know exactly what happens, but something messes up with the variable tip. calcTip() works correctly and calculates the tip amount successfully. I know this because the JavaScript console displays the amount when I input tip;. However, on the page, #tipSpan displays the tip as undefined.
What baffles me most is that the variable total works perfectly fine.
Does anyone know what might be going on or how I can fix it?
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tipping App</title>
<style>
<!-- Temporary -->
#error {
display: none;
}
</style>
</head>
<body>
<div id="wrapper">
<header>
<h1>Tipping App</h1>
</header>
<section>
<div class="price">
<h2>Price Information</h2>
<label for="priceInput">Enter the price below!</label><input id="priceInput" type="text"><button id="calcButton">Calculate the Tip</button>
<p id="error">Error: You need to enter the cost!<br><br>Use only numbers and decimal points, no currency symbols or letters.</p>
</div>
<div id="tipContainer" class="tip">
<h2>Tip Information</h2>
<p id="tipPara">Your tip should be... <span>$<span id="tipSpan"></span></span></p>
</div>
<div id="totalContainer" class="total">
<h2>Total Information</h2>
<p id="totalPara">Your total is... <span>$<span id="totalSpan"></span></span></p>
</div>
</section>
</div>
<script src="js/app.js"></script>
</body>
</html>
Here is the JavaScript:
///// VARIABLES
//////////////////////////////
var priceInput = document.getElementById("priceInput");
var calcButton = document.getElementById("calcButton");
var error = document.getElementById("error");
var tipContainer = document.getElementById("tipContainer");
var tipPara = document.getElementById("tipPara");
var tipSpan = document.getElementById("tipSpan");
var totalContainer = document.getElementById("totalContainer");
var totalPara = document.getElementById("totalPara");
var totalSpan = document.getElementById("totalSpan");
var tip;
var total;
///// FUNCTIONS
//////////////////////////////
function calcTip() {
var price = priceInput.value; // This is the price the user inputs
var minTip = (Math.ceil(price * .15)); // Calculates a 15% tip rounded up to the nearest dollar
var maxTip = (price * .2); // Calculates a 20% tip
if (isNaN(price) || price === "") {
// If the user doesn't enter a number
// Or doesn't enter anything,
// Then display the error message
error.style.display = "block";
return;
} else {
error.style.display = "none";
if (maxTip < minTip) {
// If the 20% tip is less than the 15% rounded tip,
// Then let's go with that 20% tip
calcTotal(price, maxTip);
tip = maxTip;
} else {
// Otherwise, let's just do the 15%
calcTotal(price, minTip);
tip = minTip;
};
};
};
function calcTotal(price, tip) {
// Add the price and the tip together to yield the total
price = parseInt(price);
tip = parseInt(tip);
total = (price + tip);
displayAmounts();
}
function displayAmounts() {
// Update the page to display the tip and the total to the user
tipContainer.style.display = "block";
totalContainer.style.display = "block";
tipSpan.innerText = tip;
totalSpan.innerText = total;
}
///// EVENTS
//////////////////////////////
calcButton.addEventListener("click", calcTip);
Also, unrelated, but does my JavaScript look good? Is it clean code? I hope to find a web development job in the near future, and I know I need to be good at JavaScript.
WORKING DEMO
Update the function arguments
function calcTotal(price, maxTip) {
// Add the price and the tip together to yield the total
price = parseInt(price);
tip = parseInt(maxTip);
total = (price + tip);
displayAmounts();
}
Here the argument tip is overriding the global variable. Replace it to maxTip as you call.
1) In function displayAmounts, pass parameters tip & total
2) Instead of
tipSpan.innerText = tip,
TRY WITH
tipSpan.innerHTML = tip;
and same for total ,
use totalSpan.innerHTML = total
instead of
totalSpan.innerText ;
Then it should work
Try changing your method definition so it passes the values in:
displayAmounts(); should become displayAmounts(tip, total);
See the fiddle here.
Also you should use parseFloat rather than parseInt assuming you'll want to be more accurate than whole numbers.
Just a small mistake!
Instead of:
calcTotal(price, minTip);
tip = minTip;
Do:
tip = minTip;
calcTotal(price, minTip);
This way tip is calculated before displayAmounts is run.
Abut your code:
This is fine with just getting started. I recommend going through w3school's tutorials on javascript. The more you use javascript, the better you will get.
If you want a learning path I would recommend taking, let me know.
innerText works only on IE. textContent is W3C-compliant, but if you want your code to be standards compliant and cross-browser safe you should use this:
while( tipSpan.firstChild ) {
tipSpan.removeChild( tipSpan.firstChild );
}
tipSpan.appendChild( document.createTextNode(tip) );
Do this for totalSpan also.

auto calculate the sum of input values with javascript

I've an html page which has many dynamically created input boxes. The number of text boxes vary each time.
I want to calculate the sum of the numbers the user has entered, and disply it. When the user delete one number the sum should auto calculate.
How can i do it with javascript?
Thanks
In jQuery something like this should work with a few assumptions:
$('.toAdd').live('change', function() {
var total = 0;
$('.toAdd').each(function () {
total += $(this).val();
});
$('#total').val(total);
});
The assumptions being that your input fields all have the class 'toAdd' and that your final input field has an ID of 'total'.
In pure JS:
var elems = document.getElementsByClassName('toAdd');
var myLength = elems.length,
total = 0;
for (var i = 0; i < myLength; ++i) {
total += elems[i].value;
}
document.getElementById('total').value = total;
Let me elaborate when I review my notes but here is a high level answer that I believe will work... (My Java Script is very rusty)...
Make the input boxes share an attribute (or use tag) so you can get a collection to walk through no matter the size... Then on the onkeyup event on every input call this function that will sum the totals. Put the result into another entry with the ID you know beforehand...
You will have to validate input because if one of them is not a number then the total will also be "NAN"
Okay here is a complete working example you can build off of that I just threw together: It obviously needs a great deal of polishing on your end...
<html>
<head>
<script language="javascript">
function AddInputs()
{
var total = 0;
var coll = document.getElementsByTagName("input")
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById("Display");
Display.innerHTML = total;
}
</script>
</head>
<body>
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<span id="Display"></span>
</body>
</html>

Categories

Resources