简体   繁体   中英

Calculating a number using a textbox

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

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.

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,

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/

imprint_quantity = document.getElementById('imprint_amount');

=

imprint_quantity = document.getElementById('imprint_amount').value();

Lemme know if that fixes it, a common enough mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM