0

I have this code

ASPX

<asp:TextBox ID="NewComent" TextMode="MultiLine" onkeyup="textEdit(this);" runat="server"></asp:TextBox>

JS

function textEdit(Inputelement) {
    var count = Inputelement.value.length;
    var newElement = document.getElementById(Inputelement.id + "_123");
    console.log(newElement);
    if (newElement == null) {
        newElement = document.createElement('div');
        newElement.setAttribute('id', Inputelement.id + "_123");
        newElement.innerHTML = (350 - count) + " letters left";
        Inputelement.insertBefore(newElement, Inputelement.parent);
        //Inputelement.appendChild(newElement);
        console.log("Inner");
    }
    else {
        newElement.innerHTML = (350 - count) + " letters left";
        console.log("Outer");
    }
}

The code is supposed to take a textbok and add a counter below it. but here is the catch. It places the div inside of it making it non visual.

Output (inspector)

<textarea name="ctl00$MainContent$QandA$ViewQA$QAListView$ctrl0$ViewQAComment$NewComent" rows="2" cols="20" id="MainContent_QandA_ViewQA_QAListView_ViewQAComment_0_NewComent_0" onkeyup="textEdit(this);">
    <div id="MainContent_QandA_ViewQA_QAListView_ViewQAComment_0_NewComent_0_123">344 letters left</div>
</textarea>

Using insertBefore and appendChild both result in the same problem, at least on Opera which basically is Chrome. So here i am, any ideas?

Thomas Andreè Wang
  • 3,379
  • 6
  • 37
  • 53

3 Answers3

2

A similar question has been already answered (link to answer).

With the way that you are using appendChild() you are appending newElement as a child element inside of Inputelement. Apart from the existing answer, replacing the insertBefore() line with the following code should also work:

Inputelement.parentNode.insertBefore(newElement, Inputelement.nextSibling);
Community
  • 1
  • 1
Kootoopas
  • 66
  • 1
  • 6
2

That should fix it:

textEdit = function(Inputelement) {
    var count = Inputelement.value.length;
    var newElement = document.getElementById(Inputelement.id + "_123");
    if (newElement == null) {
        newElement = document.createElement('div');
        newElement.setAttribute('id', Inputelement.id + "_123");
        newElement.innerHTML = (350 - count) + " letters left";

        Inputelement.parentNode.appendChild(newElement, Inputelement)
   }
   else {
        newElement.innerHTML = (350 - count) + " letters left";
   }
}

See fiddle:

http://jsfiddle.net/tc7qsaaL/

MartinWebb
  • 1,998
  • 1
  • 13
  • 15
0

jQuery's insertBefore does insert the element before, however plain old javascript has an insertBefore method as well which inserts it inside the element.

Javascript: http://www.w3schools.com/jsref/met_node_insertbefore.asp

jQuery: http://api.jquery.com/insertbefore/

ChrisGheen
  • 984
  • 6
  • 17