PDA

View Full Version : Can't check if text field exists using JavaScript and DOM



pollygw137
Aug 3rd, 2007, 01:21 AM
I have a page that dynamically adds rows to a table and the user can also delete any of the rows in no specific order. When the form is submitted I need to do some validation. I can't loop through it because the names may by out of sequence if the user deleted some lines, so I need to check whether that particular text field exists. For some reason I can't reference the newly created text fields. I tried referencing it by id and by name but I get an error saying that the text field has no properties.

This is the function that I check to see if a field exists

function chkExists(){

var d = document.form1;
var val = parseInt(d.f_maxmine.value);
var ct;

for (ct=1; ct <=val; ct++)
{

if (document.getElementById("f_MNAME"+ct) == null || document.getElementById("f_MNAME"+ct) == 'undefined')
{
alert("DOES NOT EXIST" + document.getElementById("f_MNAME"+ct).value);
}else{
alert("EXISTS" + document.getElementById("f_MNAME"+ct).value);
}

}

}//end function


This is the function that adds the rows
function addRow(){
//add a row to the rows collection and get a reference to the newly added row

var ct;
var newRow;
var oCell;

ct = document.form1.f_othcounter.value;

newRow = document.getElementById("tblOthGrid").insertRow((parseInt(ct)-1));

oCell = newRow.insertCell(0);
oCell.innerHTML = "&nbsp;&nbsp; <input type='hidden' name='f_OthLineNum"+ct+"' value='"+ct+"'><input type='text' name='f_MName"+ct+"'>";

oCell = newRow.insertCell(1);
oCell.innerHTML = "&nbsp;&nbsp; <input type='text' name='f_test"+ct+"'> &nbsp;&nbsp;<input type='button' value='Delete' onclick='setCounter(0,1); removeRow();'/>";


}// end function

this is the function that deletes a row

function removeRow(src){

var oRow = src.parentNode.parentNode;

/* src refers to the input button that was clicked.
to get a reference to the containing tr tag element,
get the parent of the parent (in this case case tr tag)
*/

//once the row reference is obtained, delete it passing in its rowIndex
document.getElementById("tblOthGrid").deleteRow(oRow.rowIndex);

}//end function

rwedge
Aug 3rd, 2007, 05:04 AM
For your chkExists() try this:

function chkExists(){
var obj, ct = 1, val = parseInt(document.getElementById('f_maxmine').value);
while (ct <= val) {
if (obj = document.getElementById("f_MNAME"+ct)) {
alert("EXISTS - " + obj.value);
} else {
alert("DOES NOT EXIST");
}
ct++;
}
} //end function

pollygw137
Aug 3rd, 2007, 05:07 PM
Thanks for your help. That functions works as well, but my fundamental problem was that I was setting the id to f_MNAME instead of f_MName!!