0

i want to create select option dynamically. i have two array "year" and "month". when user select 2011 then its respective month should be display in next drop down. for example

if we select 2009 then next drop down option should be "dec","oct","feb'

<head>




<script type="text/javascript" src="jquery-1.7.2.js"></script>


<script type="text/javascript">

$(function (){

    $('#first').change(function(){

    var year= new Array('2011','2010','2009');
    var month= new Array('jan_feb_march','jan_march_april','dec_oct_feb');

    var yearVal= $('#first option:selected').text();


for(i=0; i<year.length;i++){


    if(year[i]==yearVal){

    var months=month[i]


}


}



    var y= months.split('_');

for (z=0;z<y.length;z++){


$('#second').append("<option>'"+y[z]+"'</option>")  

    }



    })
})


</script>


</head>

<body>


<div class="menu">
<select id="first">
<option>select</option>
<option>2011</option>
<option>2010</option>
<option>2009</option>

</select>
<select id="second"></select>

</div>


</body>
1
  • how to stop appending option. if i select 2011 then it respective month is appearing perfectly. but if i select second time other year then is month is appending. i want to remove old year option. at one time one year option should be visible. Commented Jul 9, 2012 at 6:40

2 Answers 2

3

See this DEMO:

http://jsfiddle.net/rathoreahsan/vMuev/

JQUERY:

var categories = {
    "None":[{value:'3', text:'No cataegory selected'}],
    "2011":[{value:'1', text:'jan_feb_march'}],
    "2010":[{value:'2', text:'jan_march_april'}],
    "2009":[{value:'3', text:'dec_oct_feb'}]
};

function selectchange(){
    var select = $('[name=items]');
    select.empty();
    $.each(categories[$(':selected', this).text()], function(){
        select.append('<option value="'+this.value+'">'+this.text+'</option>');
    });
}

$(function(){
    $('[name=category]').on('change', selectchange);
});

Hope this will be useful :-)

Sign up to request clarification or add additional context in comments.

1 Comment

how to stop appending option. if i select 2011 then it respective month is appearing perfectly. but if i select second time other year then is month is appending. i want to remove old year option. at one time one year option should be visible
2

try this:

$("<option> some value </option>").appendTo($("#second"));

2 Comments

thank you sir, i almost there but the problem only is it keeping the old option with it and it showing value like jan_feb_march i want to make separate option for every month.
how to stop appending option. if i select 2011 then it respective month is appearing perfectly. but if i select second time other year then is month is appending. i want to remove old year option. at one time one year option should be visible

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.