Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from div with javascript: Always get undefined [duplicate]

I had this problem when I get the value from a div:

function sync(){
    var n1 = document.getElementById('editor').value;
    alert(n1);
    var n2 = document.getElementById('news');
    n2.value = n1;
}

div with id editor looks like this:

<div class='message'  id='editor' contenteditable="true" onkeyUp='sync()' style="color: black"></div>

When I put something in that div it will alert me undefined and that will also come in the textarea i paste it in too. So the problem is obviously by this:

var n1 = document.getElementById('editor').value;

What am I doing wrong?

like image 251
Sjenkie Avatar asked Nov 25 '14 16:11

Sjenkie


2 Answers

Try this

var n1 = document.getElementById('editor').innerHTML; // or innerText, or textContent
like image 73
Oleksandr T. Avatar answered Oct 12 '22 23:10

Oleksandr T.


I think it's important to note that even if <div> was a HTMLInputElement you would still keep getting undefined because your div,

<div class='message'  id='editor' contenteditable="true" onkeyUp='sync()' style="color: black"></div>

Has no value attribute, here is an example of a div with a value attribute:

<div class='message'  id='editor' value='hello'></div>

However, as mentioned in other answers, even though you have entered a value it, .value will still return undefined because <div> is a HTML element and not a HTMLInputElement.

If you really need to store some information in the value of the div you can always do something like this:

<div id="mydiv"></div>
<script>document.getElementById('mydiv').value='hello';</script>

Right after the div loads, you force 'hello' as the value.

The only reason you'd do this is if you really want to store data within the div's value and can't store it within the innerHTML because the div is visible.

If you want to store the information within your div like this:

<div id="editor">all the information i want to store</div>

Then document.getElementById('editor').innerHTML; is the correct solution, but remember that users will be able to see the information on the webpage.

like image 20
Danbardo Avatar answered Oct 12 '22 23:10

Danbardo