bu246
bu246

Reputation: 47

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>

Upvotes: 1

Views: 10422

Answers (4)

MMezlini
MMezlini

Reputation: 163

It's recommanded to add ID to the p tag and seperate values with a space

$(document).ready(function(){
  $("#btn").click(function(){
    var getVal = $("#inputValue").val() + " " ;
    $("#showInputValue").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 id="showInputValue"></p>
</div>

Upvotes: 0

Lyubomir
Lyubomir

Reputation: 20027

Use append instead of html

$(document).ready(function(){
    $("#btn").click(function(){
        var getVal = $("#inputValue").val();
        $("p").append(getVal); <--- CHANGE HERE
    });
});

append html

Upvotes: 1

ameenulla0007
ameenulla0007

Reputation: 2683

Did you mean, append value as a history of values?

If yes, append() is the answer for it.

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

Know more on it here, http://api.jquery.com/append/

Upvotes: 2

Dekel
Dekel

Reputation: 62546

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.

Upvotes: 3

Related Questions