简体   繁体   中英

Form button keeps showing results in new window

Very new to html and javascript here. I get the following form up and it calculates correctly but the result shows up in a new page. I'd like it to stay in the same page. Not sure what I did wrong here. Also, is there any way to shorten the function? Seems like a lot of work to do a simple calculation. Any help would be great.

<html>
<head>
    <title>Help!</help>
    <script type="text/javascript">
        function add(x,y){
        var x = document.add1.add2.value;
        var y = document.add1.add3.value;
        var x = Number(x);
        var y = Number(y);
        var z = x+y;
        return (z);
        }
    </script>
</head>
<body>
    <h3>Help me stack overflow you're my only hope!</h3>

    <form name="add1">
    Input first number to add: <input type="number" name="add2">
    2nd number: <input type="number" name="add3">
    <input type="button" value="Result"
    onclick = "document.write('The total is: ' + add() + '.');" />

</body>
</html>

Dont' use document.write to display data, it overwrites entire document. You don't want that. It's better to create new function which would render result into some other element:

<input type="button" value="Result" onclick="showResult('The total is: ' + add() + '.');" />

and the showResult function can be for example:

function showResult(result) {
    document.getElementById('result').innerHTML = result;
}

HTML:

<div id="result"></div>

Demo: http://jsfiddle.net/7ujzn35c/

Here are also a couple of general improvements you can make your code:

  1. move string manupulations to showResult completely:

     <input type="button" value="Result" onclick="showResult()" /> 

    http://jsfiddle.net/7ujzn35c/1/

  2. call add from inside showResults

     onclick="showResult(this.form.add2.value, this.form.add3.value)" 

    http://jsfiddle.net/7ujzn35c/2/

 <title>Help!</help>

First of all, This should be <title> Help! </title> <title> Help! </title>

Secondly, document.write function actually starts writing the entire page anew.

You should either replace onclick = "document.write('The total is: ' + add() + '.');" with

onclick = "alert('The total is: ' + add() + '.');" 

Better still, you could create a div element like so

<title> Help! </title>

<script>
.....
</script>

</header>

<body>

<div id = 'output'> </div> ...

then

 `onclick = "document.getElementById("output").innerHTML =  'The total is: ' + add() + '.';"

And don't give up. Hope this helps you

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