简体   繁体   中英

How do I keep the previous result on the page when outputting a new one?

I'm trying to keep the previously submitted value on the screen after hitting the submit button. For example, If I enter Apple and press submit, Apple appears. However, if I enter Banana , Apple disappears and is replaced by Banana . Is there a way to keep Apple on the page after I submit Banana ? Here's the HTML/JavaScript I'm using.

<!DOCTYPE html>
<html>

<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
      function showMessage() {
        var message = document.getElementById("message").value;
        display_message.innerHTML = message;
      }
    </script>
</head>

<body>
    <form> 
        Enter message: <input type="text" id="message">
        <input type="button" onclick="showMessage()" value="submit" />
    </form>
    <p> Message is: <span id="display_message"></span> </p>
</body>

</html>

I added an extra line of code at the bottom of your function to clear the text input each time "submit"is clicked.

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
    var allMessages = "";
    function showMessage(){
        var message = document.getElementById("message").value;
        allMessages += message + " ";
        display_message.innerHTML= allMessages;
        document.getElementById("message").value = "";
        }
    </script>
</head>
<body>
    <form>
    Enter message: <input type="text" id = "message">
    <input type="button" onclick="showMessage()" value="submit" />
    </form>
    <p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

You just need to join the inputs together. Depending on how you want that to appear on screen. In this example. I push each input into an array, then join the array with a comma and display the list.

If you are looking to do more complex layouts take a look at a template language for example: http://handlebarsjs.com/

<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>

JS

var entries=[];
function showMessage(){
var message = document.getElementById("message").value;
entries.push(message);
display_message.innerHTML= entries.join(",");
}

Fiddle

https://jsfiddle.net/aq676/543/

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