mikizas
mikizas

Reputation: 341

JQuery doesn't recognize dynamically generated id

I have searched for a while, but I'm not able to find the solution to this problem.

I am working with JSPs and Servlets. I run a JSP where some code is generated dynamically.

When I launch the program, I can see everything correctly. In fact I have opened the source code of the webpage, and everything seems to be correct.

In that code, it appears a <td> tag with the id PAR1.1:ED

<.td id="PAR1.1:ED" >3700.0</td>

(I have added the . here on purpose. There is no point in the code :P)

Then I have a script where I try to search that id, but it seems as if it doesn't exist.

   <script type="text/javascript">
        $(document).ready(function() {
            $(document).on("change", "input", function() {
                if( $("#PAR1.1:ED").length ){
                    alert("exists");
                }
                else{
                    alert("doesn't exist");
                }   
            });         
        });
    </script>

How can I make that tag id be detected?

Thank you very much!

Upvotes: 1

Views: 204

Answers (2)

MaDa
MaDa

Reputation: 10762

The problem is with the colon and the periods; you need to escape them in your selector:

if ($("#PAR1\\.1\\:ED").length ){
    alert("exists");
}

It's a common problem in JSF, too, where lots of generated ids have a colon inside. While it's not forbidden to use a colon as an id, it conflicts with the meaning of a pseudo-class in a CSS selector.

Upvotes: 3

DinoMyte
DinoMyte

Reputation: 8868

Try this :

The issue is that jquery selector would conflict if you are looking for an id using '#' having characters ( such as period) . If you were to use partial selectors, it would be okay.

if( $("[id^='PAR1.1:ED']").length)
{
                    alert("exists");
                }
                else{
                    alert("doesn't exist");
                }  

http://jsfiddle.net/yy21h9s1/

Upvotes: 0

Related Questions