如何在输入中添加删除一组用逗号分隔的值?

时间:2018-12-06 13:54:38

标签: javascript jquery html

HTML

<div class="wrap_temi">
    <ul class="list-inline list-unstyled">
        <li class="list-inline-item">
            <input type="checkbox" value="amici" autocomplete="off">  Amici
        </li>
        <li class="list-inline-item">
            <input type="checkbox" value="bacio" autocomplete="off">  Bacio
        </li>
    </ul>
</div>

<input name="usp-tags" id="usp-tags" type="text" value="" data-required="true" required="required" maxlength="999999" placeholder="inserisci uno o più tag..." class="usp-input usp-input-tags form-control" autocomplete="off">

我需要能够根据amici, bacio

在输入中添加/删除标签

我尝试使用.map(),但对following this answerPrimaryKeyRelatedField并不熟悉,但是我不确定如何将其应用于我的案子。

2 个答案:

答案 0 :(得分:0)

这是一种使用value来检索map的方法。

使用:checked取回所选的选项:-

$('.wrap_temi [type="checkbox"]').change(function(){

  var tags = $('.wrap_temi [type="checkbox"]:checked')
  .toArray()
  .map(x => x.value)
  .join(', ');
  
  $('#usp-tags').val(tags);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrap_temi">
    <ul class="list-inline list-unstyled">
        <li class="list-inline-item">
            <input type="checkbox" value="amici" autocomplete="off">  Amici
        </li>
        <li class="list-inline-item">
            <input type="checkbox" value="bacio" autocomplete="off">  Bacio
        </li>
    </ul>
</div>

<input name="usp-tags" id="usp-tags" type="text" value="" data-required="true" required="required" maxlength="999999" placeholder="inserisci uno o più tag..." class="usp-input usp-input-tags form-control" autocomplete="off">

答案 1 :(得分:0)

希望这就是您想要的:

$(document).ready(function() {

  $('input:checkbox').on('change', function() {

    var tags = $('input:checkbox:checked')
    .map(function() {
      return $(this).val();
    }).get().join(', ');

    $("#usp-tags").val(tags);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap_temi">
    <ul class="list-inline list-unstyled">
        <li class="list-inline-item">
            <input type="checkbox" value="amici" autocomplete="off">  Amici
        </li>
        <li class="list-inline-item">
            <input type="checkbox" value="bacio" autocomplete="off">  Bacio
        </li>
    </ul>
</div>

<input name="usp-tags" id="usp-tags" type="text" value="" data-required="true" required="required" maxlength="999999" placeholder="inserisci uno o più tag..." class="usp-input usp-input-tags form-control" autocomplete="off">