0

I'm using JavaScript to dynamically add rows to a table, I create some textboxes in each row, I've added an onkeyup event to one of my textboxes:

               var myTotal = "1";
           var spanTotal = document.createElement("span");
           spanTotal.innerHTML = "<input style=\"width:50px\" type=\"text\" name=\"total\" value=" + myTotal + ">";


spanCount.onkeyup = function ()
{
alert(spanTotal.innerHTML);
    };

then I add this span (which is rendered as an HTML textbox) to my table row. I want to have value of my dynamically created textbox, but whenever I change this textbox, initial value of this textbox is displayed in alert box (i.e. 1). Initial value of this textbox is "1", but when I change it (for instance type a 0 in textbox), again "1" is displyaed in alert box. I want to have value of my dynamically created textbox, should I give an ID to my span? how should I define spanCount.onkeyup function? where should it be defined so that I can have exact value of this textbox?

2 Answers 2

1

I created a jsFiddle. You can get value of input box using childNodes. There are other problems in code you were using spanCount istead of spanTotal.

Modified code:

var myTotal = "1";
var spanTotal = document.createElement("span");
spanTotal.innerHTML = "<input style=\"width:50px\" type=\"text\" name=\"total\" value=" + myTotal + ">";
document.body.appendChild(spanTotal);

spanTotal.onkeyup = function() {
    alert(spanTotal.childNodes[0].value);
};​ 
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer was really helpful! It save me a lot of time
1

Below modified code maybe can solve your problem:

var myTotal = 1;

/* object creation */
var span = document.createElement('span');

var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', 'total');
input.setAttribute('style', 'width:50px;');
input.setAttribute('value', myTotal);

// append each object to respective container
span.appendChild(input);
document.appendChild(span);

/* event handler */
input.onkeyup = function(){
  alert(this.value);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.