简体   繁体   English

如何以编程方式为html-select元素中的选项设置项目索引?

[英]How can I set an item index for an option in an html-select element programmatically?

I found out how to add a "dummy" entry as the first "pseudo-option" in a select element here , but now I want to set certain elements to default values in the select element. 我发现了如何增加一个“虚拟”条目中选择元素的第一个“伪选项” 在这里 ,但现在我想设置某些元素中的默认选择元素值。

Is this something best done using javascript, or can I do it right after the dynamic population of options in the select, which is like so: 这是使用javascript最好完成的事情,还是可以在select中动态填充选项之后立即执行,就像这样:

<label>From</label>
<select name="produsagefrom">
    @for (int i = 1; i <= @maxMonthsBackBegin; i++)
    {
        <option id="selItem_@(i)" value="@i">@i</option>
    }
</select>
<label>months back</label>
<label>To</label>
<select name="produsageto">
    @for (int i = 1; i <= @maxMonthsBackEndNormal; i++)
    {
        <option id="selItem_@(i)" value="@i">@i</option>
    }
</select>
<label>months back</label>

After populating the "produsagefrom" select, I want to set it to "13" and "produsageto" to "1" as default values. 填充“ produsagefrom”选择后,我要将其设置为“ 13”,将“ produsageto”设置为“ 1”作为默认值。

Is this a job for jQuery, can I do it right there with razor, or is it possible to do it in a code-behind (C#) file? 这是jQuery的工作吗,我可以用剃刀在那里完成,还是可以在代码隐藏(C#)文件中完成?

You could use JavaScript or Razor. 您可以使用JavaScript或Razor。

Here is Razor: 这是剃刀:

<select name="produsageto">
    @for (int i = 1; i <= @maxMonthsBackEndNormal; i++)
    {
        if(i == 1) {
            <option id="selItem_@(i)" value="@i" selected="selected">@i</option>
        } else {
            <option id="selItem_@(i)" value="@i" >@i</option>
        }
    }
</select>

Here is jQuery: 这是jQuery:

$('select[name=produsagefrom]').value = '13'

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

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