Doc Holiday
Doc Holiday

Reputation: 10254

Javascript pass a variable from function call to innerHtml

Ok, this might be an easy one, im just not sure how to do it. I have a main function where it's taking in an "id". This id is unique and I want to pass it over to another function that is doing a count for me and returns that count to an innerHtml span tag.

Reason for this is because I can have 5 of these open at the same time, but they will have the same span id name "editCommentsCounter"...I want them to be like "editCommentsCounter-id"

function editCommentToggle( id )
{
    theRow = document.getElementById("id"+id);
    //user = theRow.cells[0].innerHTML;
    //date = theRow.cells[1].innerHTML;
    com = theRow.cells[2].innerText ;
    comLength = theRow.cells[2].innerText.length ;

    idx = 2;
    maxlength = 250;
    count = maxlength - comLength;


        // Comment field
        cell = theRow.cells[idx];
        while( cell.childNodes.length > 0 ) cell.removeChild(cell.childNodes[0]);

        spanTag = document.createElement("span"); 
        spanTag.innerHTML = "You have <strong><span id='editCommentsCounter'>"+count+"</span></strong> characters left.<br/>"; 
        cell.appendChild(spanTag);
        element = document.createElement("textarea");
        element.id="commentsTextArea-"+id;
        element.rows="3";
        element.value = com;
        element.style.width = "400px";
        element.maxLength = "250";
        element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit('editCommentsCounter', maxlength, this);}; 
        cell.appendChild(element);

}

Basically I want to take :

   spanTag.innerHTML = "You have <strong><span id='editCommentsCounter'>"+count+"</span></strong> characters left.<br/>"; 

and make that into something like `span id='editCommentsCounter-' + id

so when I call this:

element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit('editCommentsCounter', maxlength, this);};

I call this above with editCommentsCounter with that id attached to it

See what Im saying?

Upvotes: 0

Views: 5106

Answers (1)

Mike S.
Mike S.

Reputation: 4879

Use:

document.getElementById("editCommentsCounter-" + id).innerHTML = someVal;

You have a lot there but it seems like that is what you're trying to do to write the innerHTML val. If not please tell me more in comments and I can suggest more.


I see you want to dynamically build a new span, then populate the content. One thing that is puzzling in the beginning you reference the element and concat "id"+id. Have to think about this one so apologies for too quick response; was just looking at your end result.

Setting the unique ID:

var spanTag = document.createElement("span");
spanTag.id = 'editCommentsCounter-' + id;
spanTag.innerHTML = 'You have ...' + count + '...';
document.body.appendChild(spanTag);

I hope this helps!

Upvotes: 1

Related Questions