I'm trying to change the inner HTML value of an element. I've not used jQuery really much and I'm still a novice in many aspects of its functionalities.
$('a.toggle-download').live('click', function (event) {
$.post("/ajax/toggle-download", { code: $(this).data("document"), prev_value: $(this).data("val") })
.done(function(data) {
var json = data,
obj = JSON && JSON.parse(json) || $.parseJSON(json);
if(obj['return'] == 1){
//document.getElementById("p_" + obj['code']).innerHTML = 'some text';
$("#p_" + obj['code']).html('some text');
}
});
event.preventDefault();
});
I've tried both lines, first the jQuery one through $("#p_" + obj['code'])
, which did not work and then through document.getElementById("p_" + obj['code'])
which works perfectly.
It seems I'm missing something obvious here, but still i don't understand why jquery does not work in this case!
Why does the plain old javascript work correctly, when jQuery does not?
1) jQuery itself works and it's correctly loaded. No conflicts are present: the ajax call is sent successfully and the answer is correctly received,
2) The received ID exists and it's unique
3) I'm not keen on jQuery html() method but i followed the documentation and it should work as i used it
This problem presents itself while using Chrome 27.0.1453.116 m. I didn't tested it with other versions or other browsers, but i'm quite sure to presume that's a jQuery problem rather than a browser problem. Also, i'm using php 5.3 on apache, but again these info should not be relevant to the problem.
If I missed some information you need to better understand my problem, please let me know in the comments and I'll try to answer you as soon as i can. Also, please forgive my bad grammar but I'm not a native english speaker.
as requested, here's an example of the ajax response:
{"return":1,"code":"5.43.321"}
the command console.log($("#p_" + obj['code']).length)
yields "0"
If Your id is p_x.xx.xxx
then $('#' + id)
means: element with the id p_x
and classes xx
and xxx
.
Either replace the dots with \\.
before using the string as id ore use the approach suggested by @dystroy.
When you want to select an element using an arbitrary string as ID, you'd better avoid using a '#'+yourstring
selector : in many cases this can make a selector invalid for jQuery even while your string is a valid HTML5 id.
If your id contains a dot, jQuery will interpret it as the start of a class.
Prefer this :
$(document.getElementById(yourstring))
$("[id='p_"+code+"']")
This will also work. It contains the periods in the id string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With