Skip to content
Advertisement

Problems dynamically adding to form (trying to use onChange and appendTo)

I want my form to extend in different ways depending on the selection of a drop down box.

I have got my JavaScript working so that onchanging my selection it will carry out something. But I am trying to use the appendTo() method as I have used before; for adding a single input, to work for implementing a div and a few inputs. Its not working, hence the post 😉

So I was hoping you could enlighten me as to a better method?

Here is my current code (courtesy of Mark):

var selectmenu = document.getElementById("type");
selectmenu.onchange = function() {
var chosenoption = parseInt(this.options[this.selectedIndex].value);
switch (chosenoption) {
case 1:
    $('<input type="text" value="1"/>').appendTo('#temp');
    break;
case 2:
    $('<input type="text" value="2"/>').appendTo('#temp');
    break;
case 3:
    $('<input type="text" value="3"/>').appendTo('#temp');
    break;
}
};

note: updated since answers.

here is constructed in jsfiddle

It does nothing currently.

Please help? 😀

Advertisement

Answer

I think value you are trying to case on is a string not a number

try this

$(document).ready(function(){
    $('#type').change(function() {
        if( $(this).val() != "nothing" ){
            switch ($(this).val()) {
            case "1":
                $('<input type="text" value="item 1" />').appendTo('#temp'); 
                break;
            case "2":
                $('<input type="text" value="item 2" />').appendTo('#temp');  
                break;
            case "3":
                $('<input type="text" value="item 3" />').appendTo('#temp'); 
                break;
            }
        }else{
            alert($(this).val());
        }
    });
})
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement