Link to home
Start Free TrialLog in
Avatar of goodk
goodkFlag for United States of America

asked on

Form validation

wanted to look up inputs only inside a certain TR and TD ids.  How can I do that?  thanks

function validateInput(xTable) {
    var isValid = true;

    var tblElement = document.getElementById(xTable),
         tblTrElement = tblElement.getElementById("TRNewRecord"),
            txtElements = tblTrElement.getElementsByTagName('input');

    for (var i = 0; i < txtElements.length; i++) {
        if (!isValid) break;

        var item = txtElements[i],
            val = item.value;
        // alert(item);
        alert(val);
        // do your validation here
        //   isValid = (val >= 100);
        isValid = isNumber(val);
        alert(" isvalid= " + isValid)
    }

    if (isValid) {
        // do something or do nothing, form will be submitted
        alert('All good, form will be submitted');
    } else {
        // show some kind of error to the user
        alert('Some values are lower than 100');
    }

    return isValid;
}


 <table id="mytable">
            <tr id ="TRNewRecord">
                <td>
                    Row 1
                </td>
                <td>
                    <div id="div1">
                        <input type="text" name="one" />
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    Row 1
                </td>
                <td>
                    <div id="div2">
                        <input type="text" name="two" />
                    </div>
                </td>
            </tr>
        </table>

Open in new window

Avatar of hielo
hielo
Flag of Wallis and Futuna image

Given:
<form>
    <table id="mytable">
            <tr id="TRNewRecord" class="TRNewRecord">
                <td>
                    Row 1
                </td>
                <td>
                    <div id="div1">
                        <input type="text" name="one" class="required-number" value="s"/>
                    </div>
                </td>
                <td>
                    <div id="div2">
                        <input type="text" name="two" class="optional-number" value="r"/>
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    Row 2
                </td>
                <td>
                    <div id="div3">
                        <input type="text" name="three" class="optional-number"/>
                    </div>
                </td>
                <td>
                    <div id="div4">
                        <input type="text" name="four" class="required-number"/>
                    </div>
                </td>
            </tr>
        </table>
</form>

Open in new window


The javascript code at the end will help you validate the <input> elements only in the first row (read the comments in the code).  However, if you want to traverse through all the <TR> elements, what you need to do is:
//obtain reference to the table (use its id):
var tbl = document.getElementById("mytable");

// then use its "rows" property to iterate over all the <TR> elements.
// Refer to the Collections section at:
// https://msdn.microsoft.com/en-us/library/ms532998.aspx#TOM%5FMethods
for(var i=0; i<tbl.rows.length;++i)
{
  var tr = tbl.rows[i];

 //now get the <inputs> in the current <tr>
 var txtFields = tr.getElementsByTagName('input');

 //now validate the fields for the row.
}

Open in new window


Here's a modified version of your posted code:
function validateInput(xTable) {

    /*
    // getElementById() makes sense only for document as its context since the 
    // ID must be unique throughout the document anyway.  If you really want to
    // first obtain a reference to the <table> and then search for the <tr>
    // within that table, then use <tr class="TRNewRecord"> instead, in which
    // case the code below should work.
    var tblElement = document.getElementById(xTable);
    var tblTrElement = tblElement.getElementsByClassName("TRNewRecord")[0];
    */
    
    // if you know the row's id, then use that directly and don't bother obtaining
    // a reference to the table first. Why? Because and ID must be unique throughout
    // the entire document, regardless of whether that ID is for an element within
    // a table or not.
    var tblTrElement = document.getElementById("TRNewRecord");
    
    var txtElements = tblTrElement.getElementsByTagName('input');

    // initialize empty array.  Add errors to it as you find them.
    // at the end, if it is not empty, then you know there were errors.
    var hasErrors=[];
    for (var i = 0; i < txtElements.length; i++) 
    {
        var row_id=1+i;
        var item = txtElements[i];

        if( ""===item.value)
        {
            if( item.className.indexOf("required-") >-1 )
            {
                hasErrors.push("Row "+row_id+" is a required field.");
            }
        }
        else if( item.className.indexOf("-number") >-1 && !isNumber(item.value) )
        {
            hasErrors.push("Row "+row_id+" must be numeric.");
        }
    }

    if (hasErrors.length==0) {
        // do something or do nothing, form will be submitted
        alert('All good, form will be submitted');
    } else {
        // show some kind of error to the user
        alert( hasErrors.join("\n") );
    }

    return hasErrors.length==0;
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Open in new window

Regards,
Hielo
Avatar of goodk

ASKER

would it be ok if there are more more than one tables on the form.  I only change the table name.  Do i need to append the table name for the TR records also?
Avatar of goodk

ASKER

Ok, let me ask my question a different way.

Can we iterate through this for a specified cell for a particular table and a particular input name?


<!DOCTYPE html>
<html>
<head>
<style>
table, td {
    border: 1px solid black;
}
</style>
</head>
<body>

<p>Click the button to return the number of cells in the table's first row.</p>

<table id="myTable">
  <tr>
    <td><input type="text" name="name"></td>
    <td><input type="text" name="age"></td>
  </tr>
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>
</table>
<br>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myTable").rows[0].cells.length;
    document.getElementById("demo").innerHTML = "Found " + x + " cells in the first tr element.";
}
</script>

</body>
</html>
>> Can we iterate through this for a specified cell for a particular table
Yes.  Just make sure the id is unique throughout the document.  

>>and a particular input name?
Once you have a reference to the cell that contains what you are interested in, you can "search" within that cell --ex:
// should give you an "array" of all the <input name="age"/> within the first cell of the first row.
var names = document.getElementById("myTable").rows[0].cells[0].getElementsByTagName('age');
//since there is only one named age in that cell, we use index 0
alert( names[0].value );
Avatar of goodk

ASKER

is this right? not working?

<!DOCTYPE html>
<html>
<head>
<style>
table, td {
    border: 1px solid black;
}
</style>
</head>
<body>

<p>Click the button to return the number of cells in the table's first row.</p>

<table id="myTable">
  <tr>
    <td><input type="text" name="age"></td>
   <td><input type="text" name="name"></td>
 
  </tr>
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>
</table>
<br>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
 
var names = document.getElementById("myTable").rows[0].cells[0].getElementsByTagName('age');

document.getElementById("demo").innerHTML= names[0].value ;
}
</script>

</body>
</html>
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of goodk

ASKER

Thank you so much for your help.
Avatar of goodk

ASKER

In reality this is what I was trying to get.  Now I have full control over the input fields

               

var RowOneCellCount = document.getElementById("myTable").rows[0].cells.length;
alert("CellCount=" + RowOneCellCount);

for (var j = 0; j < RowOneCellCount; ++j) {

                var inputs = document.getElementById("myTable").rows[0].cells[j].getElementsByTagName('input');
                alert(inputs[0].name);
                alert(inputs[0].value);
            }

Open in new window

Avatar of goodk

ASKER

How do I test if input does not exists?

if(??? inputs )