1

I am adding some controls dynamically to a HTML page using JavaScript. Lets say I have this

ID   Name          Type                   Is Valid
     (TextBox)     (Select/DropDown)      (CheckBox)
---  ------------  ---------------------  ----------
1    txtName_1     ddlType_1              chkValid_1
2    txtName_2     ddlType_2              chkValid_2
3    txtName_3     ddlType_3              chkValid_3
4    txtName_4     ddlType_4              chkValid_4

Now I remove some rows (e.g. row with ID 3) and add some new rows. New controls are named as ("txtName_" + "Last Row ID" + 1). So it may become

ID   Name          Type                   Is Valid
     (TextBox)     (Select/DropDown)      (CheckBox)
---  ------------  ---------------------  ----------
1    txtName_1     ddlType_1              chkValid_1
2    txtName_2     ddlType_2              chkValid_2
4    txtName_4     ddlType_4              chkValid_4
5    txtName_5     ddlType_5              chkValid_5

Now I want to iterate these controls in a for loop (1 to "Last Row ID") to generate a concatenated string. How these deleted IDs can be skipped in the loop?

haraman
  • 2,744
  • 2
  • 27
  • 50

1 Answers1

1

By applying the concept in this SO post How to check if element exists in the visible DOM, the controls IDs with skipped numbers can be checked as follows in the loop

var i;
for (i = 1; i <= lastRowID; i++;)
{
    var element =  document.getElementById('txtName'+i);
    if (typeof(element) != 'undefined' && element != null)
    {
        // control with this ID exists.
    } else {
        // control with this ID does NOT exist, SKIP it.
    }
}
Community
  • 1
  • 1
haraman
  • 2,744
  • 2
  • 27
  • 50