HONDDAACCORD HONDDAACCORD - 5 months ago 12
Javascript Question

How to get input text value in javascript

I want to output a manipulated input value of a text type input tag, but it seems to be harder than I thought it will be. I don't want to use alert or console.log kind of outputting, but appending to the page as new content. Here I didn't manipulate the input, since I'm not even able to output it, which is my first goal then.

my html code for the corresponding part is:

<div class="middle topic">

<div id="inputnav">
<button id="sendd">SEND</button>
</div>

<input type="text" value="" id="iPf">

<div id="oPf">
output
</div>

</div>


and here is the full javascript. I linked it at the end of the html before the closing body tag, after a jquery-1.12.2.min.js linking.

/*global $, jQuery, alert*/

$(document).ready(function () {
"use strict";

var inPuttext = document.getElementById("iPf").innerHTML;
var outPutfield = document.getElementById("oPf");

function appendOutput(where, what) {
where.innerHTML = what;
};

$('#sendd').click(function () {
appendOutput(outPutfield, inPuttext);
});


});

I can't figure out why it doesn't work. When I click the send button the only thing happens is that the "output" disappears from the #oPf div.

Answer
  • Use value property not innerHTML to get value from input element.
  • Get the value in click handler to get updated value.

$(document).ready(function() {
  "use strict";
  var outPutfield = document.getElementById("oPf");

  function appendOutput(where, what) {
    where.innerHTML = what;
  };
  $('#sendd').click(function() {
    var inPuttext = document.getElementById("iPf").value;
    appendOutput(outPutfield, inPuttext);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="middle topic">
  <div id="inputnav">
    <button id="sendd">SEND</button>
  </div>
  <input type="text" value="" id="iPf">
  <div id="oPf">
    output
  </div>
</div>

But, If you are using jQuery:

$(document).ready(function() {
  "use strict";
  $('#sendd').click(function() {
    $('#oPf').html($("#iPf").val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="middle topic">
  <div id="inputnav">
    <button id="sendd">SEND</button>
  </div>
  <input type="text" value="" id="iPf">
  <div id="oPf">
    output
  </div>
</div>

Comments