0

Using JavaScript to display a list of what was typed into the textarea element listed below. The values submitted are displayed for a split second, but are removed from the array right after the function is called. Would anyone care to explain why?

HTML

<!DOCTYPE html>
<html>
<head>
    <title>title</title>
    <link rel='stylesheet' type='text/css' href='template.css'>
</head>
<body>
    <header id='title'>
        <h1></h1>
        <h2></h2>
    </header>
    <div id='main_container'>
        <div id='chat'>

            <form id='messaging'>
                <textarea id='current_msg'></textarea>
                <input type='submit' value='send'>
            </form>
            <ul id='msg_list'>
            </ul>
        </div>
    </div>
    <script type='text/javascript' src='client.js'></script>
</body>
</html>

JavaScript

var msgList=[];
var form=document.getElementById('messaging');
var currentMsg=document.getElementById('current_msg');
var chat=document.getElementById('chat');
var ul=document.getElementById('msg_list');

function addText() {
    if(currentMsg.value.length>0) {
        if(msgList.length>=25) msgList.pop();
        msgList.unshift(currentMsg.value);
        currentMsg.value='';
        console.log(msgList.length);
    }

    var concat='';

    for(var index=0; index<msgList.length; index++) {
        concat+='<li>'+msgList[index]+'</li>';
    }

    ul.innerHTML=concat;
}

if(document.addEventListener) {
    form.addEventListener('submit', function() {
        addText();
    },
    false);
}else {
    form.attachEvent('onsubmit', function() {
        addText();
    },
    false);
}

1 Answers1

0

You need to understand the effects of having form:

1) User input some values

2) Once Submit the form get submitted , as you have not specified the action it will default to reload the current web page which means all inputs will be cleared

3) The html page get parsed from scratch , the JS code runs but it will only access the new values of inputs which are empty at this point

To make this work you need to remove the form tag

Malkhen
  • 14
  • 2