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. (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(开发者_StackOverflow);
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.
ignore the shabby styling, i just want functionality right now.
help please.
regards,
If you are using jQuery, I would first of all use
$("#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.
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. I've corrected optionvalue to 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.
精彩评论