LPB
LPB

Reputation: 515

Jquery adding an option to select

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?

Upvotes: 4

Views: 64175

Answers (2)

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17370

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/

Upvotes: 8

Subodh Ghulaxe
Subodh Ghulaxe

Reputation: 18651

var month = $('#DOBM').val();    
if ((( month == '01')||(month =='03')||(month =='05')||(month =='07')||(month =='08')||(month =='10')||(month =='12')) && ($("#DOBD option[value='31']").length == 0)) 
 {
        $("#DOBD").append("<option value='31'>31</option>");
 }

Or you can also do this

var month = $('#DOBM').val();
var arr = [ '01','03', '05','07', '08', '10', '12'];
if(($.inArray(month, arr) != -1) && ($("#DOBD option[value='31']").length == 0))
{
     $("#DOBD").append("<option value='31'>31</option>");
}

Or you can directly check number of days in month

var month = $('#DOBM').val();
var year = 2013;
if((Date(year, month, 0).getDate() == 31) && ($("#DOBD option[value='31']").length == 0)) {
    $("#DOBD").append("<option value='31'>31</option>");
}

Upvotes: 1

Related Questions