Vinod
Vinod

Reputation: 2311

Dynamically set the select-options while loading the page

I need to dynamically set the select options based on the one value which is getting from the controller while loading the page.

<script>
validate selectOptions();

function selectOptions(){
var healthWorkerQuestions1 = "${healthWorkerQuestions}";
if(healthWorkerQuestions1 == "6" || healthWorkerQuestions1 == "7" || healthWorkerQuestions1 == "8"){
                 alert("six to eight"); 
                 $('#questionOptions').empty();
                 var sel = document.getElementById('questionOptions');
                  for(var i = 0; i < drinker.length; i++) {
                    var opt = document.createElement('option');
                    opt.innerHTML = drinker[i];
                    opt.value = drinker[i];
                    $('questionOptions').append(opt).selectmenu('refresh');
                    //sel.appendChild(opt).selectmenu('refresh');
                   }             
        }

}
</script>

Here the loop is executing and able to see the alert box. And the select box options are not updating in the select box. I tried in two ways as follows,

$('questionOptions').append(opt).selectmenu('refresh');
sel.appendChild(opt).selectmenu('refresh');

But the options are not updating while loading the page.

The code for select box is:

<select name="questionOptions" id="questionOptions">
<option>Select</option>
</select>

After loading the page I am able to see only select option but not the dynamically appended values. How can I update the select option on page loading.

Any suggestions please..

Upvotes: 0

Views: 114

Answers (1)

Prasad
Prasad

Reputation: 686

Code is looks fine. To update the select option call the method form jQuery document ready function as mentioned below,

<script>
$(function(){
selectOptions();
});

function selectOptions(){
// Your code here....
}
</script>

Hope this will help you.

Upvotes: 1

Related Questions