2016-09-04 54 views
1

如何使輸入值顯示按鈕點擊的每個輸入而不刪除以前的輸入?jQuery獲取按鈕點擊的輸入值

$(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>

+0

的例子是工作中,摘錄作品。 – Li357

+0

@AndrewL。,再次檢查問題。他希望添加值**而不刪除舊值。 – Dekel

+0

哦,woops。感謝您將它引入我的注意:) @Dekel – Li357

回答

3

你有兩個選擇:

  1. 內容添加到以前的內容:

$(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>

  • 使用append代替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>

    您使用html將覆蓋p元素的內容。

    1

    使用append而不是html

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

    append html

    2

    你的意思是,附加價值作爲價值的歷史?

    如果是,append()就是它的答案。

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

    瞭解更多關於在這裏,http://api.jquery.com/append/

    +0

    這也是很好的檢查其他答案... – Dekel

    +0

    @Dekel,真.. :) – ameenulla0007

    相關問題