简体   繁体   English

如何将下拉值绑定到javascript数组?

[英]How to bind dropdown values to javascript array?

I am working in MVC and I have to bind dropdown values to an array in javascript. 我正在MVC中工作,我必须将下拉值绑定到javascript中的数组。 How do I do that? 我怎么做?

dropdown list- 下拉列表-

Html.DropDownListFor(m => m.MyActivityRequest.ToMonth, Model.MonthNames, new { @id = "monthToSelect" })

Javascript function: JavaScript函数:

$(document).ready(function(){ 
        $("#yearToSelect").change(function(){
            var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
            var date = new Date();
            var monthVar = date.getMonth();
            var yearVar = date.getFullYear();
            if ($(this).val() < yearVar ){
                $("#monthToSelect").find('option').remove();
                for( i = 0; i < 12; i++ ){          
                    $("#monthToSelect").append($("<option>",{
                        value: months[i],
                        text: months[i]
                    }));
                };
            }

you can see that the the array- 'months' is hard coded as of now. 您可以看到,到目前为止,数组“ months”已经过硬编码。 I want to dynamically bind the dropdown values to this array. 我想将下拉值动态绑定到此数组。

Js Fiddle Demo. Js Fiddle演示。

Inside your code place the below code appropriately. 在您的代码内部适当放置以下代码。

Better Approach: 更好的方法:

var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var option = '';

for (i=0;i<months.length;i++){
   option += '<option value="'+ months [i] + '">' + months [i] + '</option>';
}

$('#monthToSelect').append(option);

Refered from here . 这里引用。

I think you have to pass the month list from controller. 我认为您必须通过控制器的月份清单。 So in javascript you can make an ajax call and return the same list of months. 因此,在javascript中,您可以进行ajax调用并返回相同的月份列表。 You can use this list instead of array- 'months' in your javascript function. 您可以在JavaScript函数中使用此列表而不是array-“ months”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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