简体   繁体   English

Javascript:显示多个条件语句

[英]Javascript: Displaying Multiple Conditional Statements

I am making a form that asks three unrelated questions which display text after clicking the submit button. 我正在制作一个表格,询问三个不相关的问题,这些问题在单击“提交”按钮后显示文本。

All three questions contain an if-else statement; 这三个问题都包含一个if-else语句; two questions are text input and one is a selection box, followed by the submit button. 两个问题是文本输入,一个是选择框,然后是提交按钮。

I can get the form to display, but when I enter data and submit the data, a blank form is returned instead of the text I wanted (I am not trying to display an 'alert' message). 我可以显示该表单,但是当我输入数据并提交数据时,将返回一个空白表单,而不是我想要的文本(我不尝试显示“警告”消息)。

This is what I have so far: 这是我到目前为止的内容:

<!DOCTYPE HTML>
<html>
  <head>
  <title>Questions</title>

    <script type="text/javascript"> 

      function questions()
    {
    var hours, age, timeday;
    hours = document.form1.workhours.value;
    hours = pasrseInt(hours);
    age = document.form1.years.value;
    age = parseInt(age);
    timeday = document.form1.dayofweek.value;
    }

        if (hours >= 40)
        {
            document.write("Wow, what a hard worker!<br>");
        }
        else
        {
            document.write("Better work harder!<br>");
        }
        if (  age >= 65)
        {
            document.write("You are Eligible for retirement benefits<br>");
        }
        else
        {
            document.write("Sorry, no benefits yet.<br>");
        }
        if (day == "Sunday");
        {
            document.write("No need to pay the meter!<br>");
        }
        else
        {
            document.write("Better get some quarters!<br>");
        }

</script>
</head>
<body>
<form name="form1">
    How many hours have you worked? <input type="text" name="workhours"><br>
    How old are you? <input type="text" name="years"><br>
    What day is it today? 

    <select name="dayofweek">
    <option value="???">-Select a Day-</option>
    <option value="Sunday">Sunday</option>
    <option value="Monday">Monday</option>
    <option value="Tuesday">Tuesday</option>
    <option value="Wednesday">Wednesday</option>
    <option value="Thursday">Thursday</option>
    <option value="Friday">Friday</option>
    <option value="Saturday">Saturday</option>
    </select></br>
<p>
</p>
    <input type="submit" value="Submit" onClick="questions()">
</form>

</body>
</html>

The problem you have is you are not cancelling the form submission so the page is refreshing. 您遇到的问题是您没有取消表单提交,因此页面正在刷新。 Add return false to the onclick. 将return false添加到onclick。

<input type="submit" value="Submit" onClick="questions(); return false;">

Using document.write after the page load replaces the page content. 页面加载后使用document.write替换页面内容。 You should be using innerHTML to add text to the page. 您应该使用innerHTML向页面添加文本。

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

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