【问题标题】:jQuery - Get only the unique values of checked checkboxes based on an attr valuejQuery - 根据 attr 值仅获取选中复选框的唯一值
【发布时间】:2021-11-13 09:25:33
【问题描述】:

我正在遍历一些复选框并为每个选中的复选框执行 .ajax 调用。问题是每个复选框的名称属性可能是重复的。所以我只想为具有唯一名称属性的复选框设置 .ajax。

这是我的脚本

var elements = $("input:checkbox:checked")

var i = 0;
doLoop();

function doLoop() {
    if ( i >= elements.length ) {
        return;
    }

    // To get the element we are up to: $(elements[i])
    let e = $(elements[i]);
    var id = e.attr('name');
    var val = e.val();
    $.ajax({
        async : false,
        url:"import.php",
        method:"POST",
        data:{id:id, val:val},
        success:function(data) {
            //do some action
            i++
            doLoop()
        }
    });
}

我试图在这里找到一些类似的主题,但没有成功。

如果我选中了以下复选框

<input type="checkbox" class="form-check-input selected-checkbox" value="some text 1" name="smalltalk">
<input type="checkbox" class="form-check-input selected-checkbox" value="some text 2" name="smalltalk">
<input type="checkbox" class="form-check-input selected-checkbox" value="some text 3" name="smalltalk">
<input type="checkbox" class="form-check-input selected-checkbox" value="some text 4" name="smalltalk">

每个名称属性 smalltalk 应该只调用一次,而不是 4 次 .ajax 调用。

【问题讨论】:

    标签: jquery distinct-values


    【解决方案1】:

    我决定采用一种简单(不确定从性能角度来看效果如何)的方法。

    在 .ajax 成功后,我已将 id 值分配给另一个名为 cid (cid = id;) 的变量,因此我可以获取通过 .ajax 的最后一个值,然后将循环中的新值与最后一个值 (if (id != cid) {)。

    这就是我最终得到的结果

    var elements = $("input:checkbox:checked")
    var cid;
    var i = 0;
    doLoop();
    
    function doLoop() {
        if ( i >= elements.length ) {
            return;
        }
    
        // To get the element we are up to: $(elements[i])
        let e = $(elements[i]);
        var id = e.attr('name');
        var val = e.val();
        if (id != cid) {
            $.ajax({
                async : false,
                url:"import.php",
                method:"POST",
                data:{id:id, val:val},
                success:function(data) {
                    cid = id;
                    //do some action
                    i++
                    doLoop()
                } 
            });
        } else {
            s++;
            doiLoop();
            }
      }
    

    【讨论】:

      【解决方案2】:

      您可以使用 jQuery .serializeArray() 方法为您提供整个表单的数据:

      let data = $('form').serializeArray();
      console.log( data );
      

      输出:

      [{
              "name": "smalltalk",
              "value": "some text 1"
          },
          {
              "name": "smalltalk",
              "value": "some text 3"
          },
          {
              "name": "other",
              "value": "some other text 2"
          },
          {
              "name": "other",
              "value": "some other text 4"
          }
      ]
      

      您可以根据需要重新组织例如:

      let groupedData = Object.entries(data.reduce((acc, cur) => ({
          ...acc,
          [cur.name]: (acc[cur.name] || []).concat(cur.value)
      }), {}));
      console.log( groupedData );
      

      输出:

      [
          [
              "smalltalk",
              [
                  "some text 1",
                  "some text 3"
              ]
          ],
          [
              "other",
              [
                  "some other text 2",
                  "some other text 4"
              ]
          ]
      ]  
      

      演示

      let data = $('form').serializeArray();
      console.log( data );
      console.log( data.reduce((acc,cur) => ({...acc,[cur.name]:(acc[cur.name] || []).concat(cur.value)}),{}) );
      console.log( Object.entries( data.reduce((acc,cur) => ({...acc,[cur.name]:(acc[cur.name] || []).concat(cur.value)}),{}) ) );
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <form>
      SmallTalk
      <input type="checkbox" class="form-check-input selected-checkbox" value="some text 1" name="smalltalk" checked>
      <input type="checkbox" class="form-check-input selected-checkbox" value="some text 2" name="smalltalk">
      <input type="checkbox" class="form-check-input selected-checkbox" value="some text 3" name="smalltalk" checked>
      <input type="checkbox" class="form-check-input selected-checkbox" value="some text 4" name="smalltalk">
      <br><br>
      Other
      <input type="checkbox" class="form-check-input selected-checkbox" value="some other text 1" name="other">
      <input type="checkbox" class="form-check-input selected-checkbox" value="some other text 2" name="other" checked>
      <input type="checkbox" class="form-check-input selected-checkbox" value="some other text 3" name="other">
      <input type="checkbox" class="form-check-input selected-checkbox" value="some other text 4" name="other" checked>
      </form>

      【讨论】:

      • 感谢您的建议。我决定将 .ajax 中名称 attr 的值分配给另一个变量,然后在 .ajax 之前检查当前匹配是否持续。我会发布更新。
      猜你喜欢
      • 2015-10-30
      • 2014-08-13
      • 2016-03-04
      • 2014-03-30
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      相关资源
      最近更新 更多