【问题标题】:Dynamically creating multiple textboxes depending on minimum number of characters in previous textbox/ javascript/asp根据先前文本框/javascript/asp 中的最小字符数动态创建多个文本框
【发布时间】:2013-05-03 23:38:10
【问题描述】:

嗨,我有一个网络表单,我需要根据前一个文本框中的条目动态添加多个文本框。即使在前一个文本框中输入了一个字符,它也应该在它旁边生成新的文本框,而不会失去前一个文本框的焦点它应该允许我输入尽可能多的字符而不受限制.. 这是我的代码:

    getId = function ()
     {
        var id = 1;
        return function () 
        {
            id++;
        }
    }

    function CreateTextbox()
     {
        var box = document.getElementById("divCreateTextbox");
        var curr = 'txt' + getId();
        var inp = document.createElement('input');

        inp.type = 'text';
        inp.name = 'textfield';
        inp.setAttribute("id", curr);
        inp.setAttribute("minlength",'1');
        box.appendChild(inp);
        inp.setAttribute('onkeyup', 'moveOnMin(this)');
        inp.focus();

    }

    function moveOnMin(s)
     {
      if(s.value.length >= parseInt(s.getAttribute("minlength")))
      {

         CreateTextbox();
      }

上述代码的问题是,它只是允许我在一个文本框中输入 1 个字符并将焦点转移到新文本框上。每次我尝试在文本框中输入多个字符时,它都会为每个字符创建新的文本框。有什么解决办法吗??

【问题讨论】:

  • 我将函数称为

标签: javascript asp.net dynamic textbox dynamically-generated


【解决方案1】:

试试这个。

function CreateTextbox()
{
    var box = document.getElementById("divCreateTextbox");
    var curr = 'txt' + getId();
    var inp = document.createElement('input');

    inp.type = 'text';
    inp.name = 'textfield';
    inp.setAttribute("id", curr);
    inp.setAttribute("minlength",'1');
    box.appendChild(inp);
    inp.setAttribute('onkeyup', 'moveOnMin(this)');
    inp.setAttribute("textBoxAdded", "0");
    //inp.focus();

}

function moveOnMin(s)
{
    if (s.value.length == parseInt(s.getAttribute("minlength")) && s.getAttribute("textBoxAdded") == "0") 
{
        CreateTextbox();
        s.setAttribute("textBoxAdded", "1");
        s.focus();
    }
}

我已将您的代码更改为: 1. 继续关注现有的TextBox;和 2.让每个TextBox只添加一次TextBox

【讨论】:

  • 我已经在 IE 8.0 上测试过了。你在哪个浏览器上测试?
  • 加上你上面所说的“......每次我尝试在文本框中输入多个字符时,它都会为每个字符创建新的文本框。”,意味着代码在你身边工作。我刚刚做了一些改动。
  • 是的,它最初创建了一个文本框,但当我在其中输入文本时没有生成新的文本框。你看到代码 m 用来调用函数了吗?
  • 对不起,我没有在新代码中更改一些东西。它现在可以正常执行了 :)
  • 谢谢!我可以根据生成的文本框的数量在 Gridview 中动态添加列吗??
猜你喜欢
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 2015-11-04
  • 1970-01-01
  • 2012-12-28
相关资源
最近更新 更多