How to access the form element with javascript without using the element ID

advertisements

I want to access form elements by using javascript. The form is generated dynamically so the name, id of the form and the elements are variable. I want to get the id value of a textarea inside it by providing the name of the form, which is generated by a different script.

For instance:

<form method=post name=form33>
    <textarea id=466 cols=50 rows=5></textarea>
    <input name=submit33 onclick=postCmnt(33) value=Post type=button>
</form>

and I have the name of the form name "form33" and I need its textarea id that is 466 as output...

Javascript Generating The Form:

function openComment(id, msgid, div) {
    var div = document.getElementById(div);
    div.innerHTML = "<form method=post name=form"+id+">
        <textarea id="+msgid+" cols=50 rows=5></textarea>
        <input name=submit"+id+" onclick=postCmnt("+id+") value=Post type=button>
        </form>"
}

Javascript that need to access the form

Here is my attempt to access the id name of textarea by providing form name.

function postCmnt(id){
    var msgid=document.forms["form"+id].elements[0].id.value;//the text area's id
    var msg=document.getElementById(msgid).value;//value of text area
    //rest scripts goes here
}

Information:

  1. Form is not static generated by call to the function openComment()
  2. predicting number of form in a page is not possible as it depends upon user input .Though the textarea is the 1st element of the form .

You can add a hidden field that contains the msgid:

Javascript Generating The Form:

function openComment(id,msgid,div){
    var div = document.getElementById(div);
    div.innerHTML="<form method=post name=form"+id+">
        <input type='hidden' id='theid"+id+"' value='"+msgid+"'>
        <textarea id="+msgid+" cols=50 rows=5></textarea>
        <input name=submit"+id+" onclick=postCmnt("+id+") value=Post type=button>
        </form>"
}

and then just get the value directly:

function postCmnt(id){
    var msgid=document.getElementById("theid"+id).value;//the text area's id
    var msg=document.getElementById(msgid).value;//value of text area
    //rest scripts goes here
}