3

I want to get the text of the input text field on click of the go button. I have read a few tutorials on this, followed them step by step, but still failed to do so. Here is my code :

function go() {
  content.html($("#textfield").value);
}
<!DOCTYPE html>
<html>

<head></head>

<body>
  <div id="content">
    <input type="text" id="textfield">
    <button type="button" id="btn" onclick="go()">Go</button>
  </div>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</body>

</html>

May I ask what is wrong with it?

Omi
  • 3,954
  • 5
  • 21
  • 41
Titus Ng
  • 55
  • 1
  • 2
  • 7

2 Answers2

4

you can use .val() to get value of input.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<html>
<head></head>
<body>
  <div id="content">
  <input type="text" id="textfield">
  <button type="button" id="btn" onclick="go()">Go</button>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function go()
{
    console.log($("#textfield").val());
}
</script>
</body>
</html>
Dij
  • 9,761
  • 4
  • 18
  • 35
1

Two things: even though content should be a global reference to <div id="content">, you should not rely on this mechanism. That DOM reference won't have jQuery's HTML method anyway; instead, you should look the DOM node up using $('#content') or something similar. Additionally, jQuery provides a val() method to get an input value, .value is the native DOM API:

$('#content').html($("#textfield").val())
Rob M.
  • 35,491
  • 6
  • 51
  • 50