使用js从输入标记中获取多个值

时间:2015-02-04 08:34:10

标签: javascript jquery html

我试着编写一个能够生成几个"输入"的代码。标签为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'>");
});

我的问题是,在用户创建输入并填充后,

我希望得到它们的价值 - 对于每一本书和作者,

即。我想最终得到一对(书,作者)

我该怎么做?

4 个答案:

答案 0 :(得分:0)

对于数组中所有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 };
        }
     }
);

答案 1 :(得分:0)

还有额外$(没有右括号。

这对我有用

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

修改

让书籍和作者对使用jsfiddle

中的代码

要获得第一对,请从authors数组中获取第一个元素,然后从书中获取第一个元素 希望它有所帮助

答案 2 :(得分:0)

尝试这样的事情

&#13;
&#13;
$('#another-book').click(function(e) {
  console.log($('#here').find('input').map(function() {
    return this.value
  }).get());
  $('#here').append($("<input type='text' placeholder='book'>"));
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

&#13;
&#13;
    $('#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)
    });
&#13;
    <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>
&#13;
&#13;
&#13;