[英]Problem with dynamic form using jquery
I currently have my form presenting additions to the form depending onChange of my dropdown selection, however I want it also now do a similar thing on the newly presented input box, so, again using onChange() if the user inputs the number "4" say it presents 4 new inputs. 目前,我的表单根据下拉选择的Change来向表单显示添加的内容,但是我现在还希望它在新显示的输入框中执行类似的操作,因此,如果用户输入数字“ 4”,则再次使用onChange()说它提供了4个新输入。 (so i want a loop) here is what I have been trying:
(所以我想要一个循环)这是我一直在尝试的:
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');
}
};
here is the jsfiddle note - ive only been working on the first drop down selection. 这是jsfiddle注释-我只在第一个下拉选择中起作用。
ignore the shabby styling, i just want functionality right now. 忽略破旧的样式,我现在只想要功能。
help please. 请帮助。
regards, 问候,
If you are using jQuery, I would first of all use 如果您使用的是jQuery,我首先会使用
$("#options").bind("change",function(){
//your code here
});
rather than setting the .onchange property directly - setting event handlers in this way is generally discouraged, for a number of reasons. 而不是直接设置.onchange属性-出于多种原因,通常不建议以这种方式设置事件处理程序。
However, your main problem seems to be that you are trying to bind this event handler before your "options" input is even created. 但是,您的主要问题似乎是您试图在甚至创建“选项”输入之前绑定此事件处理程序。 If you use what I have suggested above, but use "live" instead, it will work even if the "options" input does not yet exist
如果您使用我上面建议的内容,但使用“实时”代替,即使“选项”输入尚不存在,它也将起作用
//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');
}
});
Also be aware that javascript is case-sensitive. 另请注意,JavaScript区分大小写。 I've corrected optionvalue to optionValue
我已经将optionvalue更正为optionValue
Note: I'm not intending to "answer" your "question" here, but trying to help a bit. 注意:我无意在这里“回答”您的“问题”,但希望有所帮助。 It seems to me that your "question" involves fixing your code, so that means that you really need a lot of answers to a lot of different questions.
在我看来,您的“问题”涉及修复代码,因此这意味着您确实需要针对许多不同问题的大量答案。 This is just one of those answers.
这只是这些答案之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.