从输入中获取值并在div中显示

时间:2016-11-13 14:13:57

标签: javascript html input vanilla-forums

我正在尝试获取输入的值并将其显示在其下的div中,同时用户正在键入。我想用香草js做。没有j查询。

我的HTML:

<div id="userInputBox">
<input id="inputText" type="text"      
placeholder="Enter your question" size = "50" onkeyup="myDisplay()"/>
</div>
<div class="displayQuestion"></div>

MY JS:

var input = document.getElementById('inputText').value;
var showQuestion = document.getElementsByClassName('displayQuestion');
function myDisplay(e){
showQuestion.innerHTML = input;
}

2 个答案:

答案 0 :(得分:1)

您可以使用VannilaJS方式,

推荐:将函数myDisplay()的名称更改为有意义的内容,例如displayQuestion()

&#13;
&#13;
var targetElm = document.getElementsByClassName('displayQuestion');
var inputElm = document.getElementById('inputText');

function myDisplay() {
  if(targetElm && targetElm.length > 0){
    targetElm[0].innerHTML = inputElm.value;
  }
}
&#13;
    <div id="userInputBox">
      <input id="inputText" type="text"      
      placeholder="Enter your question" size ="50" onkeyup="myDisplay()"/>
      </div>
    <div class="displayQuestion"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

试试这个:

function myDisplay(e) {
  var input = document.getElementById('inputText').value;
  var showQuestion = document.getElementById('displayQuestion');
  showQuestion.innerHTML = input;
}
<div id="userInputBox">
  <input id="inputText" type="text"
placeholder="Enter your question" size = "50" onkeyup="myDisplay(this.value)"/>
</div>
<div id="displayQuestion"></div>