elad.chen
elad.chen

Reputation: 2425

jQuery json value is not being appended

This is my code:

        success: function (data) {
            var jsonData = $.parseJSON(data);
            console.log("done");
            $.each(jsonData, function(key, value) {
                if (value !== "") { console.log("working on " + "#"+key+".div")
                    $("#"+key+".div").append("<pre>"+value+"</pre>");
                }
            });
        }

As you see, this is a snippet of the success callback function.

Everything works fine up to the point where value should be appended to the selector I provide. But for some reason, nothing is added.

console.log("working on " + "#"+key+".div")

Is printed, so I know the if statement is not the issue.

I believe the error lays with this line:

$("#"+key+".div").append("<pre>"+value+"</pre>"); 

But I can't tell what exactly I am missing.

Exemplary HTML :

<div id="prx1.sjc.div"></div>
<div id="prx2.sjc.div"></div>
<div id="sh1.sjc.div"></div>
<div id="sh2.sjc.div"></div>
<div id="sh3.sjc.div"></div>
<div id="sh4.sjc.div"></div>
<div id="sh5.sjc.div"></div>
<div id="sh6.sjc.div"></div>

Upvotes: 2

Views: 89

Answers (2)

MPavesi
MPavesi

Reputation: 971

The use of the dot in a id (or class) attribute it's not a good practice.

If you want to refer a id like this:

<div id="sh6.sjc.div"></div>

you have to escape the dot in this way

$("#sh6\\.sjc\\.div")

The dot is reserved in the selector syntax. In the linked reference is written:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").

Without escaping the dot you'll select an object with id "sh6" which has two classes "sjc" and "div", something like

<div id="sh6" class="sjc div"></div>

Shortcut

An interesting shortcut for escaping the jquery selector is in this article of the jQuery blog.

Checking the selectors

When you are dealing with this issues, check if the selector match some elements, using something like

console.log("Matching the id sh6.sjc.div, occurrences:"+$("#sh6\.sjc\.div").length);

It's easier to verify the correctness of the selector you're using

Upvotes: 2

Chandu
Chandu

Reputation: 82943

I assume you are trying to add content to a div with the id "#"+key Use

$("div#"+key).append("<pre>"+value+"</pre>"); 

or

$("#"+key).append("<pre>"+value+"</pre>"); //You don't need to add a tag selector, since you already have the id of the element

Upvotes: 0

Related Questions