0

How to append options when click first time on select tag? That mean select tag have no option until click it first time. I try code as below but the options not show until click second time, I want the options show immediately at the first time i click select tag. Please help me.

<select id="cbVoice" onclick="ClickMe()"></select>

function ClickMe(){
if($('#cbVoice > option').length == 0){ 
var TheOptions = "<option>Option 1</option><option>Option 2</option><option>Option 3</option><option>Option 4</option>";
        $('#cbVoice').html(TheOptions);
}

}
aynber
  • 22,380
  • 8
  • 50
  • 63
user3106691
  • 47
  • 1
  • 5

4 Answers4

0

Try this

function ClickMe(){
if($('#cbVoice > option').length == 0){ 
var TheOptions = "<option>Option 1</option><option>Option 2</option><option>Option 3</option><option>Option 4</option>";
        $('#cbVoice').empty().append(TheOptions);
}

}

DEMO

Sridhar R
  • 20,190
  • 6
  • 38
  • 35
0
$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
         .attr("value",key)
         .text(value)); 
});

Duplicate of What is the best way to add options to a select from an array with jQuery?

Community
  • 1
  • 1
GuyT
  • 4,316
  • 2
  • 16
  • 30
0

Try this:

<select id="cbVoice"></select>

<script type="text/javascript">
var $cbVoice = $("#cbVoice");
$cbVoice.on('mousedown', function(e) {
    if ($('option', $cbVoice).length == 0) {
        $cbVoice.html('<option>Option 1</option><option>Option 2</option><option>Option 3</option><option>Option 4</option>');
    }
});
</script>

Demo: http://jsfiddle.net/eeSGN/

redphx
  • 46
  • 1
  • 3
0

You could use mousedown with one(), and a simple loop for the options:

$('#cbVoice').one('mousedown', function() {
   var numOfOpts = 4, opts = [];
   for (var i = 1; i <= numOfOpts; i++) {
       opts.push( $('<option>', { text: 'Option ' + i }) );
   }
   $(this).append(opts);
});

Here's a fiddle

billyonecan
  • 20,090
  • 8
  • 42
  • 64