简体   繁体   English

使用JavaScript获取动态创建的文本框的价值

[英]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: 我正在使用JavaScript动态地向表中添加行,我在每行中创建了一些文本框,我在其中一个文本框中添加了一个onkeyup事件:

               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. 然后我将此跨度(呈现为HTML文本框)添加到我的表行。 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). 我希望拥有动态创建的文本框的值,但每当我更改此文本框时,此文本框的初始值将显示在警告框中(即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. 此文本框的初始值为“1”,但是当我更改它时(例如在文本框中键入0),再次在警告框中显示“1”。 I want to have value of my dynamically created textbox, should I give an ID to my span? 我想拥有动态创建的文本框的价值,我应该为我的跨度提供ID吗? how should I define spanCount.onkeyup function? 我该如何定义spanCount.onkeyup函数? where should it be defined so that I can have exact value of this textbox? 应该在哪里定义,以便我可以拥有此文本框的确切值?

I created a jsFiddle . 我创建了一个jsFiddle You can get value of input box using childNodes. 您可以使用childNodes获取输入框的值。 There are other problems in code you were using spanCount istead of spanTotal . 有在你的代码使用其他问题spanCount的istead 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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