如何在按键时更新一组文本字段,并避免在提交时重置表单? [英] How can I update a set of text fields on key press and avoid resetting a form on submit?

查看:88
本文介绍了如何在按键时更新一组文本字段,并避免在提交时重置表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的转换器,例如

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:

这是我尝试过的:

<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?

推荐答案

请检查此 FIDDLE .

所有需要添加的属性 data-formula 到表单元格中.

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')
        }

    });

});

这篇关于如何在按键时更新一组文本字段,并避免在提交时重置表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆