【问题标题】:Add/Remove comma-separated input values with jquery使用 jquery 添加/删除逗号分隔的输入值
【发布时间】:2016-11-28 11:27:39
【问题描述】:

我可以将 add 值输入到输入和 remove 但我想要实现的目标看起来很乱。

我有两张图片,点击后会显示他们的用户 ID。因此,当单击时,会添加一个隐藏的输入值 1。当点击另一张图片时,同样:

<input id="selective-avatars" name="avatars[]" type=hidden value="1,2" />

如果单击相同的图像,则再次删除它们的 id(例如 toggleClass 之类的东西)。这是我将两个链接拼凑在一起时面临的棘手部分。

完整的 HTML(示例):

<img src="url" id="1" class="avatar" />
<img src="url" id="2" class="avatar" />
# Should this be in the loop also? It's currently not.
<input id="selective-avatars" name="avatars[]" type=hidden />

JS:

$('.avatar').click(function(){
  let {id} = this;
  //let array = $('#selective-avatars').val().split(',');
  $('#selective-avatars').val(function(i, val){
     return [val + (!val ? '' : ',') + id];
  });
  //Removed about 8 lines as nothing works

  //$(this).toggleClass('avatar-circle-display-loop-select')
});

我试图不走反应路线,因为我想在副项目中使用纯 jquery。

我想要的只是&lt;input id="selective-avatars" name="avatars[]" type=hidden value="1,2, etc" /&gt; 去控制器。

【问题讨论】:

  • @Satpal 那会给我undefined。我所拥有的可以很好地找到 ID。
  • @Sylar:OP 的版本是完全有效且适当的 ES2015 解构赋值。
  • @T.J.Crowder 是的,刚刚意识到 ;)
  • 旁注:问题中有一个错误重复了三遍(我刚刚修复了它),id 上缺少"&lt;input id="selective-avatars name="avatars[]" type=hidden value="1,2" /&gt; 如果那是复制和-从您的代码粘贴,您可能需要仔细检查实际代码以查看它是否丢失。

标签: javascript jquery arrays ruby-on-rails-5


【解决方案1】:

看起来.avatar 元素上的id 告诉我们要在隐藏输入中包含哪些值。我会在元素上保留一个标志,并且每次都重建输入值:

$('.avatar').click(function(){
    var $this = $(this);
    $this.data("selected", !$this.data("selected")); // Will be `undefined`
                                                     // initially, which is falsy
    var value = $('.avatar')
        .filter(function() {
            return $(this).data("selected");
        })
        .map(function() {
            return this.id;
        })
        .get()
        .join(",");
    $("#selected-avatars").val(value);
});

我注意到你已经使用了 ES2015 及以上的特性,所以在 ES2015 中:

$('.avatar').click(function() {
    const $this = $(this);
    $this.data("selected", !$this.data("selected")); // Will be `undefined`
                                                     // initially, which is falsy
    const value = Array.from($('.avatar'))
        .filter(elm => $(elm).data("selected"))
        .map(elm => elm.id)
        .join(",");
    $("#selected-avatars").val(value);
});

【讨论】:

  • 谢谢。让我扫描一下您的代码以了解发生了什么。
  • 你不知道我对你那几行代码做了多少重构!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 2017-09-13
  • 2012-11-17
  • 2015-12-23
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多