简体   繁体   English

javascript,使用返回所选值的for循环的选择选项

[英]javascript, selection option using for loop that return the selected value

I'm pretty new to javascript so please bear with me.我是 javascript 的新手,所以请多多包涵。 I'm trying to create a drop down list of age choice from 1-100, with option 20 show as default.我正在尝试创建一个从 1 到 100 的年龄选择下拉列表,默认显示选项 20。 I also need to get the return value of the choice user selected so i can use to calculate the years.我还需要获取用户选择的返回值,以便我可以用来计算年份。 Here is the code i'm playing around with so far.到目前为止,这是我正在玩的代码。

    function createAgeList()
    {
        var myAgeOptions;

        for (cntr=1; cntr<100; cntr++)
        {
           myAgeOptions = myAgeOptions + "<option value=" + cntr + ">" + cntr + "</option>";
        }

        var myAgeSelect = document.getElementById('agelist');
        myAgeSelect.innerHTML = myAgeOptions;
    }

HTML code:
<form name="yearsleptform" id="yearsleptform" method="post">
  <select size="1" id="agelist" name="agelist">
  </select>
</form>
document.yearsleptform.agelist.value

This is going to return you the value they have selected.这将向您返回他们选择的值。

To set the default option:要设置默认选项:

function createAgeList()
    {
        var myAgeOptions;

        for (cntr=1; cntr<100; cntr++)
        {
           myAgeOptions = myAgeOptions + "<option value=" + cntr + " "+(cntr===20?"selected=selected":"")+ ">" + cntr + "</option>";
        }

        var myAgeSelect = document.getElementById('agelist');

Live Demo现场演示

        myAgeSelect.innerHTML = myAgeOptions;
    }

to get the selected value:获取选定的值:

document.yearsleptform.agelist.value

Live Demo现场演示

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

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