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

2

3 Answers 3

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
0
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);
0
-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>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.