Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
LPB Avatar asked Sep 03 '25 07:09

LPB


2 Answers

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/

like image 57
Hanlet Escaño Avatar answered Sep 05 '25 01:09

Hanlet Escaño


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>");
}
like image 27
Subodh Ghulaxe Avatar answered Sep 05 '25 01:09

Subodh Ghulaxe