0

我目前有我的表单根据我的下拉选择的更改显示对表单的添加,但是我希望它现在也对新显示的输入框执行类似的操作,因此,如果用户输入数字“4”,请再次使用 onChange()说它提供了 4 个新的输入。(所以我想要一个循环)这是我一直在尝试的:

var inputt = document.getElementById("options");
inputt.onchange = function(){
var optionValue = parseInt(this.value);
$('#container').empty();
for (i=0;i<=optionValue;i++)
{
$('<input type="text" value=""/>').appendTo('#container');      
}   
};

这是 jsfiddle注释 - 我只处理第一个下拉选择。

忽略破旧的造型,我现在只想要功能。

请帮忙。

问候,

4

1 回答 1

0

如果您使用的是 jQuery,我会首先使用

$("#options").bind("change",function(){
  //your code here
});

而不是直接设置 .onchange 属性 - 通常不鼓励以这种方式设置事件处理程序,原因有很多。

但是,您的主要问题似乎是您试图在创建“选项”输入之前绑定此事件处理程序。如果您使用我上面建议的内容,但改用“live”,即使“options”输入尚不存在,它也会起作用

//i've attached keyup in this example, but you could try modifying it to "change"
$("#options").live("keyup",function(e){
  var optionValue = parseInt(e.target.value);
  $('#container').empty();
  //note optionValue, not optionValue
  //note "<" rather than "<=", otherwise if you type "1" you'll get 2 inputs
  for (i=0;i<optionValue;i++) 
  {
    $('<input type="text" value=""/>').appendTo('#container');        
  }    
});

另请注意,javascript 区分大小写。我已将 optionvalue 更正为 optionValue

注意:我不打算在这里“回答”您的“问题”,而是想提供一点帮助。在我看来,您的“问题”涉及修复您的代码,这意味着您确实需要很多不同问题的答案。这只是其中一个答案。

于 2011-03-29T11:34:18.633 回答