簡體   English   中英

使用js從輸入標簽獲取多個值

[英]get multiple values from an input tag with js

即時通訊試圖寫一個代碼,將生成我幾個到HTML的“輸入”標簽

頁。

我想做這樣的事情:

<div id="here">
    <input type='text' placeholder='book'>
    <input type='text' placeholder='author'>
</div>
<button id="another-book">+</button>

每次單擊按鈕時,我想在上一個輸入之后立即向頁面添加另一個輸入。

我在帶有代碼的js文件中執行此操作:

$('#another-book').click(function (e) {
$('#here').append($("<input type='text' placeholder='book'>");
$('#here').append($("<input type='text' placeholder='author'>");
});

我的問題是,在用戶創建輸入並填充輸入之后,

我想獲得它們的價值-對於每本書籍和作者,

即我想最后獲得成對清單(書,作者)

我怎樣才能做到這一點?

對於數組中所有input s的值

$.map($("#here").find("input"),function(o,i){return $(o).val();});

編輯

對於成對清單

$.map( $("#here").find("input[placeholder='book']"),
    function(o,i){
        var book = $(o).val();
        var author = $(o).next("input[placeholder='author']").val();
        if (book == "" || author == "")
        {
           $(o).remove();
           $(o).next("input[placeholder='author']").remove();
        }
        else
        {
           return { "book": book,
                    "author": author };
        }
     }
);

有額外的$(不帶右括號。

這對我有用

$('#another-book').click(function (e){
    $('#here').append($("<input type='text' placeholder='book'>"));
});

編輯:

為了獲得書籍和作者對,請使用jsfiddle中的以下代碼

要獲得第一對,請從authors數組中獲取第一個元素,並從書籍中獲取first。 希望能有所幫助

試試這個

 $('#another-book').click(function(e) { console.log($('#here').find('input').map(function() { return this.value }).get()); $('#here').append($("<input type='text' placeholder='book'>")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="here"> <input type='text' placeholder='book'> </div> <button id="another-book">+</button> 

  $('#another-book').click(function (e) { var a = $('<input>', { text:"", type:"text", placeholder:"book" }); var b = $('<input>', { text:"", type:"text", placeholder:"author" }); var c = $('<span>',{}).append(a).append(b); $('#here').append(c); }); $('#g-val').click(function(){ var all = []; $('#here > span').each(function(){ var $book = [ $(this).find('input[placeholder=book]').val() , $(this).find('input[placeholder=author]').val() ] all.push($book); }); console.log(all) }); 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="here"> <span> <input type='text' placeholder='book'> <input type='text' placeholder='author'> </span> </div> <button id="another-book">+</button> <h4 id="s-value"></h4> <button id="g-val">get all input[type=text] ...</button> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM