user3023566
user3023566

Reputation: 169

How can I update a set of text fields on key press and avoid resetting a form on submit?

I'm trying to make a simple converter like this one, but in JavaScript, where you enter an amount in tons and it displays a bunch of different numbers calculated from the input, sort of like this:

A table of values relating to tons of cardboard, trees saved, etc.

This is what I've tried:

<html>
    <head>
        <title>Calculator</title>
        <script type="text/javascript">
            function calculate(t){
                var j = document.getElementById("output")
                var treesSaved = t.tons.value * 17;
                j.value = treesSaved;
            }
        </script>
    </head>
    <body>
        <form>
            <input type="text" placeholder="Tons" id="tons" />
            <input type="button" value="Calculate" onclick="calculate(this.form)" />
            <br />
            <input type="text" id="output" value="Output" />
        </form>
    </body>
</html>

This works, to the extent that when you press the button, it calculates and displays the right number. However, it also seems to reset the form when I press the button, and I'm hoping to eliminate the need for the button altogether (so on every key press it recalculates).

Why is the form resetting, and how could I extend this to not need the button at all?

Upvotes: 2

Views: 934

Answers (4)

effe
effe

Reputation: 1365

Please check this FIDDLE.

All you need to adding attributes data-formula to your table cells.

HTML

<table border="1">
    <tr>
        <td>
            <input type="text" id="initial-val" />
        </td>
        <td>card board</td>
        <td>recycled</td>
        <td>reusable</td>
    </tr>
    <tr>
        <td>lovely trees</td>
        <td data-formula='val*5'></td>
        <td data-formula='val+10'></td>
        <td data-formula='val/2'></td>
    </tr>
    <tr>
        <td>what is acres</td>
        <td data-formula='val*2'></td>
        <td data-formula='val*(1+1)'></td>
        <td data-formula='val*(10/5)'></td>
    </tr>
</table>

JAVASCRIPT

  $(function () {

    function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

    var $input = $('#initial-val'),
        $cells = $('td[data-formula]');

    $input.on('keyup', function () {

        var val = $input.val();

        if (isNumber(val)) {
            $.each($cells, function () {
                var $thisCell = $(this);
                $thisCell.text(
                    eval($thisCell.attr('data-formula').replace('val', val.toString()))
                )
            });
        } else {
            $cells.text('ERROR')
        }

    });

});

Upvotes: 1

Furquan Khan
Furquan Khan

Reputation: 1594

Here is the fiddle link for it:

Calculator

Use the below code to achieve what I think you want to :

<html>
    <head>
        <title>Calculator</title>
        <script type="text/javascript">
            function calculate(t){

            var j = document.getElementById("output");
            var rege = /^[0-9]*$/;
            if ( rege.test(t.tons.value) ) {
                var treesSaved = t.tons.value * 17;
                j.value = treesSaved;
            }
            else
                alert("Error in input");
            }
        </script>
    </head>
<body>
    <form>
        <input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
            <input type="button" value="Calculate" onclick="calculate(this.form)" />
            <br />
            <input type="text" id="output" value="Output" />
        </form>
    </body>
</html>

Upvotes: 2

scribblemaniac
scribblemaniac

Reputation: 6859

Assuming your calculations are all linear, I would suggest that you create an array of the coefficients and then just loop that array to do the calculation and print it out. Something like this:

HTML:

<table>
 <tr>
  <th></th>
  <th>Recycled Cardboard</th>
  <th>Re-usable Cardboard</th>
 </tr>
 <tr>
  <th>Trees Saved</th>
  <td></td><td></td>
 </tr>
 <tr>
  <th>Acres Saved</th>
  <td></td><td></td>
 </tr>
 <tr>
  <th>Energy (in KW)</th>
  <td></td><td></td>
 </tr>
 <tr>
  <th>Water (in Gallons)</th>
  <td></td><td></td>
 </tr>
 <tr>
  <th>Landfill (Cubic Yards)</th>
  <td></td><td></td>
 </tr>
 <tr>
  <th>Air Pollution (in Lbs)</th>
  <td></td><td></td>
 </tr>
</table>

Javascript:

function showStats(cardboardTons) {
    var elements = $("td");
    var coeffs = [17, 34, 0.025, 0.5, 4100, 8200, 7000, 14000, 3, 6, 60, 120];
    for(var i=0;i<coeffs.length;i++)
        elemnts.eq(i).html(cardboardTons * coeffs);
}

Once you get input from the user, pass it into the showStats function as a number and it will go through all of the cells in the table and calculate the proper number to go in it.

Upvotes: 1

JayD
JayD

Reputation: 6521

You'll need:

  1. a drop down option that allows the user to select what type of calculation they want to do and then display an input field OR multiple input fields
  2. an input field for user input
  3. a submit button with a onclick() event which passes your input into your calculation (you may want to do some validation on this so they can only enter numbers) validation examples
  4. your Javascript file that takes the input from your box on submit and performs your calculation
  5. display the information back to user... something like innerHtml to an element you've selected or:

    var output = document.getelementbyid("your outputbox")
    output.value = "";
    output.value = "your calculated value variable";
    

Here is a tutorial for grabbing user input.

Upvotes: 1

Related Questions