【问题标题】:How to write all input types values in span on change using javascript/jquery?如何使用 javascript/jquery 在更改时写入所有输入类型值?
【发布时间】:2019-03-02 07:01:34
【问题描述】:

我有一个输入类型列表,一个组合 <input type="checkbox"><input type="text">

每当我选择一个复选框时,它都会将其值放入

<span name="products" id="products"></span>

以逗号分隔。

但我不知道如何包含 &lt;input type="text" /&gt; 的值 所以每当我输入一个值时,它也会将它的值添加到

<span name="products" id="products"></span>

请帮助我。 我的代码:

Javascript

$(function() {
  $('input[name=selectProducts]').on('change', function() {    
    $('#products').text($('input[name=selectProducts]:checked').map(function() {
      return this.value;
    }).get());
  });
});

HTML

<input type="checkbox" name="selectProducts" id="product1" value="product1" />
<input type="checkbox" name="selectProducts" id="product2" value="product2" />
<input type="checkbox" name="selectProducts" id="product3" value="product3" />
<!-- i want to include these input type text -->
<input type="text" name="selectProducts" id="product4" value="product4" />
<input type="text" name="selectProducts" id="product5" value="product5" />
<span name="products" id="products"></span>

输出

product1,product2,product3,product4,product5

这里唯一起作用的是复选框。请帮我在输入文本中做。

【问题讨论】:

    标签: javascript jquery html html-input


    【解决方案1】:

    您应该将 type=text 输入添加到 jquery 选择器。

    $('input[name=selectProducts]:checked, input[name=selectProducts][type=text]')
    

    所以你的代码应该改为

    $('input[name=selectProducts]').on('change', function() {
        $('#products').text($('input[name=selectProducts]:checked, input[name=selectProducts][type=text]').map(function() {
            return this.value;
        }).get());
    });
    

    $('input[name=selectProducts]').on('change keyup', function() {
      $('#products').text($('input[name=selectProducts]:checked, input[name=selectProducts][type=text]').map(function() {
        return this.value;
      }).get());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="checkbox" name="selectProducts" id="product1" value="product1" />
    <input type="checkbox" name="selectProducts" id="product2" value="product2" />
    <input type="checkbox" name="selectProducts" id="product3" value="product3" />
    <input type="text" name="selectProducts" id="product4" value="product4" />
    <input type="text" name="selectProducts" id="product5" value="product5" />
    <span name="products" id="products"></span>

    【讨论】:

    【解决方案2】:

    试试这个代码

    $(() => {
        var prods = $("span#products");
        $("input[type='text'], input[type='checkbox']").change((el) => {
          if(!el.target.checked && el.target.type=="checkbox") return;
          else{
            prods.html(prods.html() + el.target.value);
          }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 2022-07-01
      • 2011-04-02
      • 1970-01-01
      • 2018-05-12
      • 2014-12-04
      • 1970-01-01
      相关资源
      最近更新 更多