简体   繁体   中英

How to get value from firebase database show in p element

I'm trying to create chat app using firebase database. I have html:

<input type="text" name="txt" id="txt">
<button type="submit" id="btn-send" onclick="addElement()">SEND</button>
<p id="list-message"></p>

and javascript :

var rootRef = firebase.database();
var message = rootRef.ref().child('/message');

function addElement() {
    var x = document.getElementById('txt').value;
    var node = document.createElement("li");
    var text = document.createTextNode(x);

    node.appendChild(text);
    document.getElementById('list-message').appendChild(node);
    message.push().set({
        Message: $("#txt").val()
    });
}

Screenshot of my Firebase data

。

How can I retrieve all the data and show as a list in <p id="list-message"></p> ?

Add a data listener which looks out for changes in the message node then update <p id="list-message"></p> .

message.on('child_added', function(snapshot) {
  var msg = snapshot.val();
  var msgDiv = document.createElement("div");
  msgDiv.textContent = msg.Message;
  document.getElementById("list-message").appendChild(msgDiv);
});

Refer to this codelab for more on how to build a chat app: https://codelabs.developers.google.com/codelabs/cloud-firebase-chat/ .

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