Hey Guys

Ive had my first go at writing with Jquery, i know VERY basic JS and
jquery is making life a lot easier, but not easy enough it seems....

So my task was to write a script to calculate a number of input fields
and display the total in another input, which ive managed to do. Also
it needed to notify the user if the total went above 100, which ive
also figured out.
The part im stuck on, is making sure that only numbers get passed in,
and displaying an alert if the user inputs anything other than a digit
from 1-9. Probably sounds easy for you guys, if so, can you please
enlighten me.

Also, if you see any ways that my code can be simplified, please let
me know. Im all about having the least code possible!

So here it is:

JS:

        $(document).ready(function() {

                function setTotal(event) {
                        var value = 0;

                        $("input.inputAdd").each(function() {
                                var inputAddVal = $(this).val()
                                if (inputAddVal != '') {
                                        value = eval(value) + eval(inputAddVal);
                                }
                        });

                        $("input.inputSub").each(function() {
                                var inputSubVal = $(this).val()
                                if (inputSubVal != '') {
                                        value = eval(value) + eval(inputSubVal);
                                }
                        });

                        $("input.inputTotal").val(value)

                        if (value > 100) {
                                $("input.inputTotal").addClass("error")
                                alert('The total must add up to 100%')
                                }
                        else {
                                $("input.inputTotal").removeClass("error")
                                }
                }

                $("input.inputAdd").bind("change", setTotal)
                $("input.inputSub").bind("change", setTotal)

                setTotal();
        });


HTML (very simple for testing only):

<form>

        <input class="inputAdd" type="text" style="width: 20px" /><br />
        <input class="inputAdd" type="text" style="width: 20px" /><br />
        <input class="inputAdd" type="text" style="width: 20px" /><br />
        <input class="inputAdd" type="text" style="width: 20px" /><br />
        <input class="inputAdd" type="text" style="width: 20px" /><br />

        TOTAL:
        <input class="inputTotal" type="text" />

</form>

Reply via email to