简体   繁体   中英

Error in Code, missing basics in JS

Hi I'll try to keep it short... Last week we started learning Javascript in School. Before we learned HTML, CSS and Java(i know it has nothing to do with JS i just want to mention I should know the syntax, from what our teacher told us).

So we started with doing Drop-Down-Lists for a form to choose a day, a month and a year. The code then looked like this:

    Day:
    <select name="day">
        <script type="text/javascript">
            var day;

            for(i=1;i<=31;i++){
                day += "<option value='"+i+"'>"+i+"</option>";
            }

            document.write(day);
        </script>
    </select>

This worked. But our teacher told us one of the nice things about Javascript is to make everything simplier with methods, etc. to avoid rewritting things. We had to do this Drop-Down for a month and a year too, so I thought I would make a function in an external Javascript File.

This is the function:

    function date(start, end) {

     var dateV ="";

       for(start==i;i<=end;i++)
       dateV += "<option value='"+i+"'>"+i+"</option>";

    document.write(dateV);
    }

Then i call it in the HTML File:

    Day:
    <select name="day">
        <script type="text/javascript">
            date(1,31);
        </script>
    </select>

But this just displays an empty Drop Down menu. What did i do false? I just want to know it to understand the basics of Javascript, because i would really like to learn this script languague.

Thanks for your help.

PS: Sorry for my english mistakes, not my main language...

Check out your date() function:

function date(start, end) {

    var dateV ="";

    //  vvvvvvvv
    for(start==i;i<=end;i++)
        dateV += "<option value='"+i+"'>"+i+"</option>";

    document.write(dateV);
}

(variable == value) is conditional, and returns true if the variables are equal, and false if they're not. You want to change start == i to var i = start which means " start the loop by creating a variable i and set it to the value of start "

In turn, you'd end up with the following:

function date(start, end) {

    var dateV ="";

    for(var i = start;i<=end;i++)
        dateV += "<option value='"+i+"'>"+i+"</option>";

    document.write(dateV);
}

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