Jquery adding an option to select
append, jquery, select
Solution
Your if statement is wrong. You have to compare the `.val()` with each value as such:
if($('#DOBM').val() == '01'||$('#DOBM').val() == '03'
EDIT
Optionally you could also use the switch statement:
$("#btn").on("click",function(){
switch($("#DOBM").val())
{
case "01":
case "03":
case "05":
case "07":
case "08":
$("#DOBD").append("<option value='31'>31</option>");
break;
}
});
JSFiddle: http://jsfiddle.net/dRJHh/
With array, as per @sberry suggestion:
var vals = ['01','03', '05', '07', '08'];
$("#btn").on("click",function(){
if(jQuery.inArray($("#DOBM").val(),vals) > -1)
{
$("#DOBD").append("<option value='31'>31</option>");
}
});
jsFiddle: http://jsfiddle.net/yhcDa/
Problem
I have tried solutions on other questions answered on stackoverflow, but none of them worked for me. In a form, I want to update the number of days in a month depending on the month that the user chooses. `#DOBM` is the ID of the month select list (DOBM stands for Date Of Birth Month) `#DOBD` is the ID of the day select list (DOBD stands for Date Of Birth Day) Basically, if `#DOBM` has values of 01,03,05,07,08,10,12, we are in a month with 31 days. Here is my code: ``` if ((($('#DOBM').val() == '01'||'03'||'05'||'07'||'08'||'10'||'12')) && ($("#DOBD option[value='31']").length == 0)) { $("#DOBD").append("<option value='31'>31</option>");} ``` The second line of code is to see if the option already exists in the day select list. The last line of code is to append the new option (day 31) if we are in a month of 31 days AND if option 31 doesn't already exist. The code just doesn't update the DOBD select list. Any idea on what I am doing wrong?