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

时间:2012-04-07 06:00:42

标签: javascript

我对javascript很新,所以请耐心等待。我正在尝试从1-100创建一个年龄选择的下拉列表,默认选项20显示。我还需要获取所选用户的返回值,以便我可以用来计算年份。这是我到目前为止所玩的代码。     

    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>

2 个答案:

答案 0 :(得分:0)

document.yearsleptform.agelist.value

这将返回他们所选择的值。

答案 1 :(得分:0)

设置默认选项:

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;
    }

获取所选值:

document.yearsleptform.agelist.value

<强> Live Demo