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

goodkAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
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
goodkAuthor Commented:
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?
goodkAuthor Commented:
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>
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

hieloCommented:
>> 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 );
goodkAuthor Commented:
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>
hieloCommented:
Note: When pasting code, please click on the "Code" option at the top and then paste your code within the code tags.  It's easier to refer to "Line x" if you put it in Code tags.

Read the comments in the code.
<!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 id="Row1">
    <td><input type="text" name="age" value="20"></td>
   <td><input type="text" name="name"></td>
 
  </tr>
  <tr id="Row2">
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>
 <tr id="Row3">
    <td><input type="text" name="age" value="21"></td>
   <td><input type="text" name="name"></td>
 
  </tr>
 </table>
<br> 

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

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

<script>
function myFunction() {

//getElementsByName() and getElementById() operate on "document". So don'
var names = document.getElementsByName('age');
for(var i=0;i<names.length; ++i)
{
	 alert( names[i].value );
	 alert( names[i].parentNode.parentNode.id);
}

//getElementsByTagName() operate on a context node.
// the line below should have been "...TagName", not "...Name".  I apologize for the oversight
var inputs = document.getElementById("myTable").rows[0].cells[0].getElementsByTagName('input');
alert( inputs[0].name )
document.getElementById("demo").innerHTML= inputs[0].value ;
}
</script>

</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
goodkAuthor Commented:
Thank you so much for your help.
goodkAuthor Commented:
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

goodkAuthor Commented:
How do I test if input does not exists?

if(??? inputs )
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.