views:

331

answers:

3

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.

+1  A: 

According to your code "myMsgs" should be something like this (in javascript):

var myMsgs = [{"id_chat_message":"id1"},{"id_chat_message":"id2"},{"id_chat_message":"id3"}];

Which would mean this will let you get at the divs you want:

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

But there is probably a better way to do what you want.

Can you provide some more details?

David Murdoch
perfect generic approach!
Andreas Niedermair
+1  A: 

the simplest approach would be: add a class-property, which you can then access via jQuery - eg.

var messageBoxes = $('.mySpecialCssClass');

you can now iterate over this array and do something with jQuery/javaScript!

Andreas Niedermair
I agree. classes FTW.
David Murdoch
A: 

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);
}
Brandon Montgomery
Thanks for your explanation. I should have thought of that beforeI dont test it but i'am sure it will work.
Ewerton