Georgiana M
Georgiana M

Reputation: 431

JavaScript event button onclick works only one time

I want to fire an onclick event from a button. The event is declared in a separate JavaScript file.

The code must reproduce a chat. If I send first text it works fine, but if I try to send something again (second text) it does not fire.

The html file contains:

var chatOutputDiv = document.getElementById("chatOutput");
chatSubmit.onclick = function () {
        // Create a Json object with "displayname" being the display name and "messageText" the message.
        // "displayname" is taken from URL, message from element chatInput.
        //var chatMessage = { "displayname": getURLParameter("displayName"), "messageText": chatInput.value };
        // We send data on the "chat", channel which is currently hard-coded
        // in later versions we allow custom naming of channels.
        //conference.sendData("chat", chatMessage);
        // Send text in current chat
        chatOutputDiv.innerHTML += "<br> user : message";
        // Clear chat input
        chatInput.value = "";
    };
<div class="row">
    <div class="col-xs-12 col-lg-12 col-sm-12 col-md-12" align="center">
        <div id="chatOutput" style="height: 200px; width: 220px; overflow-y: scroll;">
            <input type="text" id="chatInput"/>
            <input id="chatSubmit" type="button" value="Send"/>
        </div>
    </div>
</div>

If you try this code, it works one time, but after that it doesn't work anymore. It seems that it doesn't fire the event.

Upvotes: 0

Views: 5185

Answers (1)

Grim...
Grim...

Reputation: 16953

It's because you are recreating the html inside .chatOutput when you click the button, so the HTML (which includes the button) is rewritten and the event is lost.

There are various ways around this. One would be to make the function a named function that you call, and adding chatSubmit = document.getElementById("chatSubmit"); chatSubmit.onclick = myFunctionName; to the end of your function.

However, I think a nicer way of doing it is to just use an extra div to store the response, like so:

<div class="row">
<div class="col-xs-12 col-lg-12 col-sm-12 col-md-12" align="center">
    <div id="chatOutput" style="height: 200px; width: 220px; overflow-y: scroll;">
        <input type="text" id="chatInput"/>
        <input id="chatSubmit" type="button" value="Send"/>
        <div id="chatResponse"></div>
    </div>
</div>
</div>


var chatOutputDiv = document.getElementById("chatOutput")
var chatSubmit = document.getElementById("chatSubmit")
var chatResponse = document.getElementById("chatResponse");
var chatInput = document.getElementById("chatInput");

function foobar() {
    chatResponse.innerHTML += "<br> user : " + chatInput.value;
    chatInput.value = "";
}

chatSubmit.onclick = foobar;

Fiddle: https://jsfiddle.net/r0gm30mr/

Upvotes: 2

Related Questions