简体   繁体   中英

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

I'm pretty new to javascript so please bear with me. I'm trying to create a drop down list of age choice from 1-100, with option 20 show as default. 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

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