bu246 bu246 - 3 months ago 25
HTML Question

jQuery get input value on button click

How to make input value showing every input on button click without deleting the previous input ?



$(document).ready(function(){
$("#btn").click(function(){
var getVal = $("#inputValue").val();
$("p").html(getVal);
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<fieldset>
<legend>jQuery input value</legend>
<input id="inputValue" type="text" name="text">
</fieldset>
<button id="btn">display value</button>
<p></p>
</div>




Answer

You have two options:

  1. Add the content to the previous content:

$(document).ready(function(){
  $("#btn").click(function(){
    var getVal = $("#inputValue").val();
    $("p").html($("p").html() + " " + getVal);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <fieldset>
    <legend>jQuery input value</legend>
    <input id="inputValue" type="text" name="text">
  </fieldset>
  <button id="btn">display value</button>
  <p></p>
</div>

  1. Use append instead of html:

$(document).ready(function(){
  $("#btn").click(function(){
    var getVal = $("#inputValue").val();
    $("p").append(getVal);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <fieldset>
    <legend>jQuery input value</legend>
    <input id="inputValue" type="text" name="text">
  </fieldset>
  <button id="btn">display value</button>
  <p></p>
</div>

You usage of html overrides the content of the p element.