简体   繁体   中英

Javascript Validate Text Boxes with Error IF all three text boxes <> then 100%

I have a Form which contains 4 text boxes, I need help with validation.

I need that the total combined value be = 100%, if less or greater then show error.

eg

Box 1 user enters 50%, Box 2 user enters 30% and Box 3 user enters 19%. Box 4, would hold the total value of box 1,2 and 3 ie Total 99% When the user clicks submit, it should validate and return error eg, total not equal to 100% Same goes if the total of box 4 is > the 100%

At the moment i have it calculating the total value for box 4, but not sure how to do the validation!

    <SCRIPT language="JavaScript">

function CalculateCardT()
{
    formSectionA.CardTotal.value = 

parseFloat(formSectionA.strPercDeferredGoods.value) + parseFloat(formSectionA.strPercDeposits.value) + parseFloat(formSectionA.strPercSubscriptions.value);


    }
    </SCRIPT>


          <tr>
        <td rowspan="2" nowrap="nowrap"> % of CARD turnover</td>
        <td nowrap="nowrap">% Deferred delivery of goods</td>
        <td nowrap="nowrap">% Deposit is taken</td>
        <td nowrap="nowrap">% Subscriptions</td>
        <td nowrap="nowrap">% Total</td>
      </tr>
      <tr>
        <td nowrap="nowrap">
          <input name="strPercDeferredGoods" type="text" required="required" id="strPercDeferredGoods" tabindex="6" onBlur="CalculateCardT();"  onChange="CalculateCardT();" size="3" maxlength="3" /></td>
        <td nowrap="nowrap">
          <input name="strPercDeposits" type="text" required="required" id="strPercDeposits" " tabindex="7" onBlur="CalculateCardT();" onChange="CalculateCardT();" size="3" maxlength="3" />
         </td>
        <td nowrap="nowrap">
          <input name="strPercSubscriptions" type="text" required="required" id="strPercSubscriptions" tabindex="8"  onblur="CalculateCardT();" onChange="CalculateCardT();" size="3" maxlength="3"/></td>
        <td nowrap="nowrap">
          <input name="CardTotal" type="text" id="CardTotal" style="background-color:#CCC" size="3" maxlength="3" onKeyDown="return false;"/></td>
      </tr>

BTW. Im a noob and useing Dreamweaver so please go easy on the code!

First - the code that you're using is outdated and there are syntax errors.

Here is a shorter version of syntactically correct HTML

<table>
    <thead>
        <tr>
            <th>% Deferred delivery of goods</th>
            <th>% Deposit is taken</th>
            <th>% Subscriptions</th>
            <th>% Total</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <input type="text" id="strPercDeferredGoods" />
            </td>
            <td>
                <input type="text" id="strPercDeposits" />
            </td>
            <td>
                <input type="text" id="strPercSubscriptions" />
            </td>
            <td>
                <input type="text" id="CardTotal" disabled="disabled" />
            </td>
        </tr>
    </tbody>
</table>

And the JavaScript, which I commented what it's doing on every line so you can learn from it:

// IIFE - create local "document"
(function (document) {

    // Store all of the "input" elements in the variable "elems"
    var elems = document.getElementsByTagName("input");

    // Store an array of id's of the items to sum in the variable "idsToSum"
    var idsToSum = ["strPercDeferredGoods", "strPercDeposits", "strPercSubscriptions"]

    // Loop through the "input" elements
    for (var i = 0; i < elems.length; i++) {

        // For each "input" element, add a "change" event listener
        // When the event happens, run the function
        elems[i].addEventListener("change", function () {

            // Define a variable "sum" and assign a value of 0 to it
            var sum = 0;

            // Loop through all of the "idsToSum"
            for (var a = 0; a < idsToSum.length; a++) {

                // If the value of the current input is a number (removing the % sign if applicable), then add the value to the "sum" variable.  Otherwise, add 0
                sum += isNaN(parseFloat(document.getElementById(idsToSum[a]).value.replace("%", ""))) ? 0 : parseFloat(document.getElementById(idsToSum[a]).value.replace("%", ""));
            }

            // If the value of "sum" is greater than 100
            if (sum > 100) {

                // Clear the "CardTotal" value
                document.getElementById("CardTotal").value = "";

                // Alert an error
                alert("Total is not equal to 100%");
            }

            // Otherwise
            else {

                // Assign the value of "CardTotal" to the value of "sum" and add a % sign
                document.getElementById("CardTotal").value = sum + "%";
            }
        });
    }

// IIFE - pass in global "document"
})(document);

Note: Your JavaScript should be placed just before the HTML end body </body>

Here is a working example:

 (function (document) { var elems = document.getElementsByTagName("input"); var idsToSum = ["strPercDeferredGoods", "strPercDeposits", "strPercSubscriptions"] for (var i = 0; i < elems.length; i++) { elems[i].addEventListener("change", function () { var sum = 0; for (var a = 0; a < idsToSum.length; a++) { sum += isNaN(parseFloat(document.getElementById(idsToSum[a]).value.replace("%", ""))) ? 0 : parseFloat(document.getElementById(idsToSum[a]).value.replace("%", "")); } if (sum > 100) { document.getElementById("CardTotal").value = ""; alert("Total is not equal to 100%"); } else { document.getElementById("CardTotal").value = sum + "%"; } }); } })(document); 
 input{width:96%;} table,th,td{border:1px solid black; border-collapse:collapse;} 
 <table> <thead> <tr> <th>% Deferred delivery of goods</th> <th>% Deposit is taken</th> <th>% Subscriptions</th> <th>% Total</th> </tr> </thead> <tbody> <tr> <td> <input type="text" id="strPercDeferredGoods" /> </td> <td> <input type="text" id="strPercDeposits" /> </td> <td> <input type="text" id="strPercSubscriptions" /> </td> <td> <input type="text" id="CardTotal" disabled="disabled" /> </td> </tr> </tbody> </table> 

Also - you really should have no reason to use Dreamweaver. Take the time to learn the code. It's really quite simple and there are a ton of free resources and tutorials out there for both HTML and JavaScript.

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