简体   繁体   中英

Append data in select (option) got from server

I am trying to append the data got from Server via AJAX task in the select options but whenever the append function get executed by clicking the select Button(Day) each time the data get appended like this: 1, 2 ,3.... 1, 2, 3 Means the same data gets appended multiple times (ie each time when button is clicked).

   <div class="form-group col-sm-3 d-inline-block" style="padding: 0px;">
    <select class="form-control" id="Day" name='day' onclick="get_max_np_date()">
        <option disabled selected>Day</option>
        <script>
            var max_day;
            function get_max_np_date() { //Return the maximum Days in Nepali Date System (Bikram Sambat)
                var get_year = document.getElementById('Year') 
                var get_month = document.getElementById('Month'); 
                
                year = get_year.options[get_year.selectedIndex].value;
                month = get_month.options[get_month.selectedIndex].value;
                console.log(Boolean(year && month));
                if (year && month){
                    $.ajax({
                        url: 'max-np-day',
                        type: 'get',
                        data: {
        
                        'year':year,
                        'month':month
        
                        },
        
        
                        success: function (data) {
                            max_day = data;
                            var days;
                            DayElm = document.getElementById("Day")

                            for (days = 1; days <= max_day; days++) {
                                var optionElm = document.createElement("option");
                                var daysNode = document.createTextNode(days);
                                optionElm.appendChild(daysNode)
                                DayElm.appendChild(optionElm)
                            }
                              
                        }
                        
                        })
                }
        
            };
            </script>
        </select>
</div>

I understood your requirement as you've told me in FB . It's simple...

  1. Pass id's of Month and Year in their respective select tag.

  2. Ue on change function

    $( "#{{Month}}, #{{Year}}" ).on( "change", function() { ....CODE STUFF .... })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM