0

I have a div which contains message updates sent by users. How can I assign a javascript variable to this div so that it's value is always the current content of the div which is consistently updating with messages?

var x = document.getElementById("MessageBox"); // only equals value at the 
// time rather than present value
10
  • where and how are you getting the new data? Commented Feb 2, 2015 at 7:09
  • poll it to get the values for a certain interval. You cant get the values like referencing the div element in one variable. Commented Feb 2, 2015 at 7:09
  • Either you can add a script block after the html region that gets updated and assign the new value to the variable or you can add a polling to your page which continuously monitor the value change. Commented Feb 2, 2015 at 7:10
  • 1
    x.innerHTML should give you the current value. right? Commented Feb 2, 2015 at 7:10
  • The new data is received from user's input. It's a very basic websocket chat and I'm trying to create a variable which has the text value of the content of the div. Commented Feb 2, 2015 at 7:11

2 Answers 2

4

The easiest way to accomplish this would be to assign an .onchange event handler to the element, then assign the node's value to a variable held outside the scope of the function:

var myMSGvalue;
document.getElementById("MessageBox").onchange = function () {
    myMSGvalue = this.value;
    // this will work for <input>, not <div>
}

If you really need to assign your data to an html element, you should use an <input type="hidden">.

However, it would be much better to assign the data to a variable before you append it to the page. For example, let's say you have a web socket:

var messages = [];
socket.on("msg", function (msg) {
    messages.push(msg);
    // msg: { content: "Hello!", author: "notSure" };
    functionToAppendToPage(msg);
})

Now, you can see all the messages received in messages and messages[messages.length - 1] will return the last message received (provided at least one message has been received).

Sign up to request clarification or add additional context in comments.

3 Comments

Typo in the handler. msMSGvalue
does div support onchange event? I think it supports only <input type="checkbox">, <input type="file">, <input type="password">, <input type="radio">, <input type="range">, <input type="search">, <input type="text">, <keygen>, <select> and <textarea> - w3schools.com/jsref/event_onchange.asp
Hey roy, now when I type myMSGvalue in the console it gives me back 'undefined'
3

If your message box field getting data using any Api or through Ajax. You can update the variable before assigning value to message box.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.