1

I am trying to validate a form using Javascript. The validation function aims to iterate through a variable number of input elements which have been named using an array format so that they come through properly in $_POST. However, I'm having trouble iterating through these elements with Javascript - does anybody know how to access these from simple Javascript?

Here's my validation function and a cut down version of my form to help illustrate what I'm trying to do:

<script type="text/javascript">
function validateForm() {
    var vTotal = parseInt(document.getElementById('Total'));
    var subtotal = 0;

    var sub = document.getElementsByName('subqty');
    for ( var i = 0; i < sub.length; i++ ) {
        if ( sub[i].value != "" ) {
            subtotal += parseInt(sub[i].value);
            }
        }

    if ( subtotal != vTotal ) {
        alert("Totals do not match, please check your math and try again.");
        return false;
        }
    }
</script>

....

<form name="test" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validateForm();">
<input type="text" id="Total" value="100"><br>

<!-- there can be any number of subtotal inputs -->
<input type="text" name="subqty[1]" value="30"><br>
<input type="text" name="subqty[2]" value="10"><br>
<input type="text" name="subqty[3]" value="43"><br>

<input type="submit" value="Check Validation">
</form>

So far I am receiving an error that the parser cannot read the property "length" of type NULL - so it would appear that using getElementsByName on an array of input elements is not valid? Is there another way to do this?

4
  • 2
    None of your elements have the name subqty, so nothing matches. Just give the elements a common class, and use that instead. Javascript and HTML doesn't really care about "array named" elements, only PHP (and some other serverside languages) do. Commented Feb 3, 2017 at 23:26
  • Also, grouping inputs is generally for radio buttons and the like, for your text inputs you really should just use regular names. Commented Feb 3, 2017 at 23:29
  • @adeneo Grouping would be done by giving them the same name, which isn't the case here anyway. Indexing them is a common approach for arbitrarily many inputs, e.g. in lists. Commented Feb 3, 2017 at 23:32
  • @adeneo Thanks, that did work - switched to getElementsByClassName() and assigned the elements a common class. Bergi is right, naming inputs as arrays in this case is necessary because it is a dynamic form which can shrink or grow based on user action Commented Feb 3, 2017 at 23:38

2 Answers 2

1

Use CSS Attribute-Begin-With Selector like this:

var sub = document.querySelectorAll("[name^='subqty']");

More CSS selectors here.

Sign up to request clarification or add additional context in comments.

Comments

0

HTML

<form name="test" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validateForm();">
    <input type="text" id="Total" value="100"><br>
        <div id="subForm">
            <!-- there can be any number of subtotal inputs -->
            <input type="text" name="subqty[1]" value="30"><br>
            <input type="text" name="subqty[2]" value="10"><br>
            <input type="text" name="subqty[3]" value="43"><br>
       </div>
    <input type="submit" value="Check Validation">
</form>

JavaSript

function validateForm() {
    var vTotal = document.getElementById('Total').value;
    var subtotal = 0;

    var sub = document.querySelectorAll('#subForm input');
    for ( var i = 0; i < sub.length; i++ ) {
        if ( sub[i].value != "" ) {
            subtotal += parseInt(sub[i].value);
        } else {
            alert('Please fill all fields!');
        }
    }

    if ( subtotal != vTotal ) {
        alert("Totals do not match, please check your math and try again.");
        return false;
        } else {
            alert('Everything is wright!');
            return true;
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.