Search code examples
javascriptjqueryonchange

JQuery onClick Pre-Populate


I am trying to do the following - could anyone help me out?

I need to pre-populate the "Date" select dropdown from a comma delimited text field.

<select id="place">
   <option>Manchester</option>
   <option>London</option>
</select>

<select id="date">
</select>

So basically this is what I am looking for ...

OnChange "listener" for Place, when "Place" changes it will get the text field "Place.txt" so for example, if I select London, it will get "London.txt". This will contain a txt file with comma delimited values ie. Date1, Date2, Date3 etc.

This then needs to pre-populate the "Date" with each date.


Solution

  • $("#place").change(function(){
         var fileName = $("select option:selected").text() + ".txt";
    
         $.get(fileName, function(data) {
           var dates = data.split(",");
           var str = "";
           $.each(dates,function(index,value){
                str += "<option>"+value+"</option>";
           });
           $('#date').html(str);
         });
    });
    

    try this. untested you may have to play with it a little bit but this is the general idea