user94628
user94628

Reputation: 3721

Select array from checkbox value with Jquery

I have a checkbox set to checked:

<input type="checkbox" value="24hrs" name="timeformat[]" id="isCheckedFormat" checked>

<select class="form-control" name="Mon1" id="mon1"></select>

I try to do a JQuery so that if it's checked it uses an array with certain values and if it's not checked than with different array values.

if ($('#isCheckedFormat').is(':checked')true){ 
    var vals = [1,2,3,4,5];           
}else{
     var vals = ['a','b','c','d','e'];    
 }

These then populate select fields:

for(var i = 0; i<vals.length; i++) {
$('#mon1').append('<option val="'+vals[i]+'">'+vals[i]+'</option>'); 
}

At the moment the 'select option' doesn't get populated by either values from the array vals

JSFiddle

Upvotes: 0

Views: 73

Answers (2)

Davie Brown
Davie Brown

Reputation: 717

Be careful with the scope of your vals array. see: http://jsfiddle.net/52jw5Lpv/7/

You are having a problem since you are defining the array inside the if statement, which means it doesn't exist outside it. See my link for a fix. Note that the array/var has been defined before the if statement.

Also - note that on the initial load, the values aren't currently reflected - so you'll need to sort that. Also - Multiple check/uncheck will continually append the values, so that needs fixed aswell. (Guess these are separate issues which you should be able to sort)

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

You have a type in if statement. use:

if($('#isCheckedFormat').is(':checked'))

Upvotes: 3

Related Questions