I am totally new to coding. Please help.I am obtaining tweet text using node.js and displaying using html. When I input new text the result should replace earlier result in #tweets and not append to it
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
#<input type="text" id="tag" class="hash"/>
<button>submit</button>
</form>
<div id="tweets"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="/socket.io/socket.io.js"> </script>
<script>
var socket = io.connect('/link');
$('.hash').on('keypress',function(){
setTimeout(function(){
$('#tweet').empty();
socket.emit('message', $('#tag').val());
},2000);
return;
});
socket.on('message', function(msg){
$('#tag').val('');
$('#tweet').empty();
$('#tweets').after($('<div>').text(msg));
});
</script>
</body>
<html>
Replace .after with .html:
$('#tweets').html($('<div>').text(msg));
If I understand you correctly just use text or innerHTML.
For Example:
...
socket.on('message', function(msg){
$('#tag').val('');
$('#tweet').html(msg); //OR
$('#tweet').text(msg);
});
...
Is there also perhaps a misspelled JQuery selector? I cannot find the element "#tweet." It appears in both your timeout and in the socket event handler. I'd personally go with this instead, esp if there is a selector spelling issue.
$("<div />", {
text: msg
}).appendTo($("#tweets").empty());
EDIT: I like SlyBeaver's gist. I thought you needed an inner div for some reason. Rather than deal with .empty().append().chain().a().bunch().of().stuff(), I'd just do for plain text:
$("#tweets").text(msg);
or if the tweet contains HTML, use this or it will not be parsed as such:
$("#tweets").html(msg);
Change
$('#tweets').after($('<div>').text(msg));
to use .html() in jquery
$('#tweets').html($('<div>').text(msg));
document.getElementById('tweets').innerHTML = 'Your content';