Vote count:
0
What's wrong with this?
<button id='myButton'>Click me</button>
<p>Borken</p>
<div id='RS_msgBox'></div>
<hr />
<!-- This is the control. The structure is exactly the same as when after
the JS gets done .appending to #RS_msgBox -->
<p>Works</p>
<div id='RS_msgBox2'>
<div id='RS_msgs2'>
<textarea id='RS_text2' cols=50 rows=5>
I was here before any JS affected me.
</textarea>
</div>
</div>
jQuery('#myButton').click(function () {
var msgDiv = jQuery("#RS_text"),
msgDiv2 = jQuery("#RS_text2"),
logOne = '\nI am the first log entry. ',
logTwo = "\nHey, where is the first entry? ";
jQuery("#RS_msgBox").append("<div id='RS_msgs'><textarea id='RS_text' cols=50 rows=5>I was via JS append().</textarea></div>");
// Experiment
console.log('Before:'+msgDiv.val());
msgDiv.val(msgDiv.val()+logOne); // Doesn't work because msgDiv.val() is undefined at this point. But why?? I 'defined' it when I .append()ed it, didn't I?
console.log('After:'+msgDiv.val());
// Control
msgDiv2.val(msgDiv2.val()+logOne);
// Appending further text still fails whether we call another function or not.
anotherFunc(logTwo);
});
function anotherFunc(newText) {
var msgDiv = jQuery("textarea#RS_text"),
msgDiv2 = jQuery("textarea#RS_text2");
msgDiv.val(msgDiv.val()+newText);
msgDiv2.val(msgDiv2.val()+newText);
}
tl;dr: Why can't I .append()
a <textarea>
to a <div>
and set a .val(logOne)
to it immediately? More importantly, how to fix/work around?
--
I've found answers on SO that almost answer my question, but none really explain WHY the recently created <textarea>
doesn't get appended, or HOW to work around it.
In other words, I'm certain that this is a duplicate question by now, but I haven't found the one that answers my two questions (why? & how?).
I'm guessing that the browser needs a little time to .append()
the <textarea>
to the DOM, and the code works asynchronously. In other words, the code just "skips" setting the .val(logOne)
because #RS_text
isn't ready yet (no errors thrown, caught or handled), and it just continues on it's merry way to setting .val(logTwo)
to #RS_text2
.
Does anyone know if that sounds anywhere near correct?
Ultimately, I suppose what's more important is how to fix/work around this. The goal is to have a text area created for the sole purpose of receiving notes/log entries from the remainder of the javascript (via node and socket.io). And this code DOES work on the second time around, when the <textarea>
has been created and a new log entry is sent to it.
Aucun commentaire:
Enregistrer un commentaire