0

I'm trying to create a text field that displays the input right after "go" button is pressed. But when I press the button it clears out all the elements.

HTML

<div id = "sideMenu">
  <ul>
    <li id="r">
      <span><img class="piece" src="vazirRed.png"></span>
      Red Player<input type="text" id="input" value="name">
      <button onclick="write();">go</button>
    </li>
    <li>
      <span><img class="piece" src="vazirBlue.png"></span>
      Blue Player<input type="text" value="name">
      <button onclick="write();">go</button>
    </li>
  </ul>
</div>

JS

function write(){
  var inputRed=document.getElementById("input");
  var redName = inputRed.value;
  var name = document.createElement("div");
  name.appendChild(redName);
  //document.getElementById("#r").innerHTML += redName;
}

The fiddle

Cilan
  • 13,101
  • 3
  • 34
  • 51
ArdMir
  • 7
  • 3
  • Note: The `onLoad` option in JSFiddle affects the scope of the JavaScript you input. [Simple example doesn't work on JSFiddle](http://stackoverflow.com/questions/5431351/simple-example-doesnt-work-on-jsfiddle) – Jonathan Lonowski Jul 18 '14 at 16:58
  • Since IDs are supposed to be unique, you should not be appending an input with the same ID back into the DOM. – Diodeus - James MacFarlane Jul 18 '14 at 16:58

3 Answers3

1

You're just using the write keyword for your function. Then it's calling document.write(), which will replace everything by an empty string.

Replace it by anything else :

function writeIt() {
    ...
}

Update JSFiddle

Side notes :

  • Use document.getElementById("r") instead of document.getElementById("#r")
  • Select "No wrap in " in your Fiddle to get inline calling to work
zessx
  • 68,042
  • 28
  • 135
  • 158
0

You can't name a function as write().

If you will call onclick=write() the function document.write() being called. So your DOM is being cleared. And you are not getting anything.

Rename your function.

Put this line in function to add div in body

document.body.appendChild(name);
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
-1

you can't use method write, because The write() method writes HTML expressions or JavaScript code to a document. doc: http://www.w3schools.com/jsref/met_doc_write.asp

so, please change for your method become like this :

<div id = "sideMenu">
  <ul>
    <li id="r">
      <span><img class="piece" src="vazirRed.png"></span>
      Red Player<input type="text" id="input" value="name">
      <button onclick="submitInput();">go</button>
    </li>
    <li>
      <span><img class="piece" src="vazirBlue.png"></span>
      Blue Player<input type="text" value="name">
      <button onclick="submitInput();">go</button>
    </li>
  </ul>
</div>
<script>
function submitInput(){
  var inputRed =  document.getElementById("input");
  var redName = inputRed.value;
  var name = document.createElement("div");
  //name.appendChild(redName);
  document.getElementById("r").innerHTML += redName;
}
</script>