Reputation: 47
I've been trying to calculate a number using a number given by a user in a text box. I've been trying to use the following code. But when I try to test it, nothing happens. Is there something I'm missing? And is there a way that I can make the imprint variable global?
<form>
<p>How many products do you want
ingraved?<input id="imprint_amount" name="imprint_amount" type="text"/>
</p>
<p>Names to be Imprinted(one per
line)<TEXTAREA COLS=25 NAME="imprint_text" ROWS=5 WRAP=HARD style="resize:none;"></textarea>
</p>
<input onclick="imprint_price" type="button" value="Finish"/>
<p id="total_cost"></p>
</form>
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quality,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount');
imprint_total = $imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost') = "$" + imprint_total;
}
Thanks, Traci
Upvotes: 1
Views: 1584
Reputation: 2843
Change your javascript to:
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quantity,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount').value;
imprint_total = imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost').innerHTML = imprint_total;
}
</script>
Working jsFiddle here http://jsfiddle.net/Zt38S/2/
Upvotes: 1
Reputation: 4188
imprint_quantity = document.getElementById('imprint_amount');
=
imprint_quantity = document.getElementById('imprint_amount').value();
Lemme know if that fixes it, a common enough mistake.
Upvotes: 0
Reputation: 2822
In this line, you'll want to set the innerHTML
of the element.
document.getElementById('total_cost').innerHTML = "$" + imprint_total;
This basically sets the text inside the <p></p>
to be <p>$x.xx</p>
.
And also this line should be
imprint_quantity = document.getElementById('imprint_amount').value;
which retrieves the value from the textbox.
Furthermore, when defining the variables, you wrote "quality". It should be
imprint_quantity,
Upvotes: 1
Reputation: 665545
You will want to use the value
property of that input element you are referencing in your variable:
… parseInt(imprint_quantity.value, 10);
For arbitrary HTML elements, you need to use textContent
(or innerText
to support old IE):
document.getElementById('total_cost').textContent = …;
Assigning to an expression as you did should have thrown a quite accurate exception, check your browser's error console for them.
Upvotes: 2