Javascript – string concatenation inside jquery selectors

asp.netjavascriptjqueryjquery-selectors

I am developing a application in C#, ASP.NET and I have a lot os divs in my page, each div is a container for a chat message and each div have a unique id: like this

"<div id='" + myMsgs[j].id_chat_message + "' style='padding: 10px;'>"

so, each div have the same id in page and in database.

now a want to find some div, with jquery, but it doesnt work

        for (var j = 0; j < myMsgs.length; j++) {
        findDiv = $('#<%= ' + myMsgs[j].id_chat_message + '.ClientID%>');
    }

i know that my problem is the concatenation of the strings, but i dont know how to solve it.

Best Answer

When you try to use server tags in the aspx page like that, you are telling ASP .NET to process the page during rendering and replace all those tags with their corresponding values or evaluations. Since you're trying to build the string inside the server tags dynamically using JavaScript, ASP .NET isn't going to process that string and you'll end up with code like this:

$("#<%=id1.ClientID %>")

ASP .NET only processes this type of tag when it renders the page (which is already finished), and this is running on the client-side only, so this isn't going to work.

You should be able to just do this:

for (var j = 0; j < myMsgs.length; j++) {
  findDiv = $('#' + myMsgs[j].id_chat_message);
}