1

I'm struggling to get my javascript to work, what I'm trying to do, is create a dropdownlist with javascript and then populate it with values before adding it to a div.

I managed to get the code to work when it was just the for loop, but since I tried to create the list and add it to the div it no longer works.

var numberOfAdults = ["Adults (18+) ", "1", "2", "3", "4", "5", "6", "7", "8"];
                alert($(this).val());
                var numberOfRooms = $(this).val();
                switch (numberOfRooms) {
                    case "1":
                        //$('#AdultsRoom1').show();
                       // var list = document.createElement('select');
                       // list.setAttribute("id", "HotelRoom2");
                       // var adult = document.getElementById('HotelRoom2');
                        for (var i = 0; i < numberOfAdults.length; i++) {
                           var list = document.createElement('select');
                           list.setAttribute("id", "HotelRoom2");
                            var opt = document.createElement('option');
                            opt.innerHTML = numberOfAdults[i];
                            opt.value = numberOfAdults[i];
                            list.appendChild(opt);
                            $('#HotelRoom3').html(list);
                        }
                        break;
                } 

Thanks for any help

1
  • first beware that an id MUST be unique, so when you run this loop twice, it creates an invalid one; second, use .append(list) to add it to the dom; third, look into the console: any errors? Commented Jun 11, 2014 at 11:11

1 Answer 1

1

I came up with this fiddle from the code you provided. It seems to be working now.

window.onload = function () {
    var numberOfAdults = ["Adults (18+) ", "1", "2", "3", "4", "5", "6", "7", "8"];
    //alert($(this).val());
    var numberOfRooms = "1";
    switch (numberOfRooms) {
        case "1":
            var list = document.createElement('select');
            list.setAttribute("id", "HotelRoom2");
            for (var i = 0; i < numberOfAdults.length; i++) {
                var opt = document.createElement('option');
                opt.innerHTML = numberOfAdults[i];
                opt.value = numberOfAdults[i];
                list.appendChild(opt);
            }
            $('#HotelRoom3').html(list);
            break;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks csanonymus seems I was almost there, just code on wrong lines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.