简体   繁体   中英

Do nothing if an input field is empty and if it has a value check to see if it is numeric and display an alert if it is not

I am trying to make a form that automatically sums input fields on blur and displays the sum in an inactive "Total:" field. I don't want to run anything if a user puts focus in an input then moves focus away without inputting anything and if a user does input something I want to restrict the field to only numbers. If there is a better way of doing this, please let me know. Here is an example of my current approach:

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Test Calc</title>
        <script src="javascript.js"></script>
    </head>
    <body>
        <h1>Sales By Month</h1>
        <form method="get">
            <label for="january">January:</label>
            <input type="text" id="january" class="amount" onblur="isNum(); calculateSum();">
            <label for="february">February:</label>
            <input type="text" id="february" class="amount" onblur="isNum(); calculateSum();">

            <label for="total">Total:</label>
            <input type="text" id="total" disabled>
        </form>
    </body>
</html>

JavaScript

function calculateSum() {

    var elems = document.getElementsByClassName('amount');

    var myLength = elems.length;
    sum = 0;

    for (var i = 0; i < myLength; ++i) {
        sum += elems[i].value *1;
    }

    document.getElementById('total').value = sum;

}

function isNum() {
    var amounts = parseInt(document.getElementsByClassName('amount').value);

    if (isNaN(amounts) == true && amounts != '') {
        alert("Please enter a numeric value");
    }

}

The calculation function currently works but the "Please enter a numeric value" alert pops up every time I tab away from a field regardless of the contents.

First you need to test the value of the element that losts focus, which means you should pass it in the argument like this

onblur="isNum(this); calculateSum();"

then in your isNum function in javascript remove document.getElementsByClassName and use the argument instead ... and don't test if amounts != '' because it will never be equal to empty string while you do this amounts = parseInt(elem.value); you have to test on the elem.value

function isNum(elem) 
{
   var amounts = parseInt(elem.value);

   if (isNaN(amounts) == true && elem.value != '') {
     alert("Please enter a numeric value");
}

Here is a jsFiddle

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