简体   繁体   中英

Get value of dynamically created textbox using JavaScript

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 (ie 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?

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);
};​ 

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM