tags:

views:

470

answers:

2

This is driving me nuts!

I am trying to access a TextArea inside the GridView control. The TextArea is popped up when a button on a gridview is clicked. For some reason the textarea.value always contains " ".

<asp:GridView ID="gvCategories" runat="server" AutoGenerateColumns="false" 
            onrowcommand="gvCategories_RowCommand">

    <Columns>
    <asp:TemplateField>
    <ItemTemplate>
        <input type="button" value="add comment" onclick="showCommentBox()" />
    </ItemTemplate>
    </asp:TemplateField>

     <asp:TemplateField>
    <ItemTemplate>
       <div id="commentBox" style="display:none">

     <input type="button" value="move comment input box" onclick="moveComment()" /> 


    <textarea id="txtComment" rows="10" cols="30">
    </textarea>

    </div>   
    </ItemTemplate>
    </asp:TemplateField>

    </Columns>

    </asp:GridView>




function moveComment() {

        alert(document.getElementById("txtComment").value);  

    }

I have added this code on the server side but the TextBox always returns " "

  protected void gvCategories_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            var row = (GridViewRow) (e.CommandSource as LinkButton).NamingContainer;
            var description = (row.FindControl("txtDescription") as TextBox).Text;
            lblComment.Text = description; 
        }
A: 

try textarea.innerHTML

looking at your code that would be:

alert(document.getElementById("txtComment").innerHTML);
j0tt
Tried it! It returns nothing!
azamsharp
I think that is because that id is not unique seeing as how there is one per row in your ItemTemplate. You need to add a unique prefix based on row id.
j0tt
Thanks! Actually my main purpose if to access the Text of the TextBox on the server side. I have replaced TextArea with TextBox but when the postback happens it return " " in the TextBox.Text property: <asp:TextBox ID="txtDescription" runat="server" />
azamsharp
Please see the above code it has been edited!
azamsharp
Nevermind. I see the code above. I missed that. Do you see the values output on the client. Is this a data issue?
j0tt
+2  A: 

@Azam - This is related to your other post which I answered. The gridview is generating the commentBox DIV along with all its child elements multiple times with the same set of IDs.

I ran a test on this and found that each call to document.getElementById("txtComment") returns the next matching element in the DOM with that Id until it cycles through the entire collection of matching elements, going back to the first one and then it does it all over again.

This is the reason why you get a blank when trying to access the value of the textarea or textbox for that matter.

You need to modify your call to showComment() so that it stores a reference to the element in the given row, then when you call moveComment(), it will work on the same element and not just the next element in the DOM with the same ID.

Jose Basilio