【问题标题】:Update Array with dynamically generated values使用动态生成的值更新数组
【发布时间】:2021-11-22 05:09:44
【问题描述】:

我对 JavaScript 很陌生,所以我很难解决这个相对简单的问题:

我编写了一个函数,如果用户单击添加或删除按钮,它会动态地向 DOM 添加或删除下拉字段。到目前为止一切顺利,直到这里一切正常。

现在我想收集数组中的数据以将其发送到 api。 使用以下代码我可以收集它,但我很难弄清楚如何从数组中删除特定值。

<div class="container mt-2" id="stores">
                            <div class="row">
                                <div class="col">
                                    <h2>Marktet</h2>
                                    <div class="col-form-label storesHint">Select at least one market</div>
                                </div>
                            </div>
                            <div id="form">
                                <div>
                                    <div id="addAnotherMarket">
                                    <div class="marketRow">
                                    <select class="form-control" id="market" name="market">
                                      <option value="1"> market1</option>
                                      <option value="2"> market2</option>
                                      <option value="3"> market3</option>
                                      <option value="4"> market4</option>
                                      <option value="5"> market5</option>
                              
                                    </select>
                                    <input class="deleteButton" type="button" id="remove" value="" style="display: none; font-family: FontAwesome, 'Helvetica Neue', Helvetica, Arial, sans-serif;">
                                    </div>
                                    </div>
                                </div>
                            </div>
                            <div>
                                    <div class="addBtnContainer">
                                        <div class="centerBtn">
                                        <a class=" button btn_gray buttonWithIcon" id="add">
                                            <i class=" fa fa-plus icn" id="btnIcon" style="font-size: 16px;" aria-hidden="true"></i> 
                                            <span class="btnText spn" style="top:0px !important">Add another market</span>  
                                        </a> 
                                        </div>
                                </div>  
                            </div>
                        </div>
$(document).ready(function () {
  let index = 0;
  let store = {};
  let stores = [];
  var oldValue = [];
  window.Stores = stores;

  //set initial value for the first dropdown element
  store = { "store_id": parseInt($('#market').val(), 10) };
  stores.push(store);
  oldValue[index] = store;
  //update value if user changes first element
  $('#market').on('change', function () {
    store = { "store_id": parseInt($(this).val(), 10) };
    var eleIndex = stores.indexOf(oldValue[index]);
    if (eleIndex !== -1) {
      stores.splice(eleIndex, 1, store);
      oldValue[index] = store;
    }
  });
  //add a new dropwdown element 
  $("#add").click(function () {
    index++;
    $(this).parent().parent().before($("#form").clone().attr("id", "form" + index));
    $("#form" + index + " :input").each(function () {
      $(this).attr("name", $(this).attr("name") + index);
      $(this).attr("id", $(this).attr("id") + index);
    });

    //set initial value of the new dropdown element    
    store = { "store_id": parseInt($('#market' + index).val(), 10) };
    stores.push(store);
    oldValue[index] = store;
    //set new value if user changes value
    $('#market' + index).on('change', function () {
      store = { "store_id": parseInt($(this).val(), 10) };
      var eleIndex = stores.indexOf(oldValue[index]);
      if (eleIndex !== -1) {
        stores.splice(eleIndex, 1, store);
        oldValue[index] = store;
      }
    });

    //add remove button    
    $("#remove" + index).css("display", "inline-flex");
    $(".marketRow").css({
      'display': 'flex',
      'align-items': 'center',
      'margin-top': '5px'
    });

    //if user clicks remove button delete value from array
    $("#remove" + index).click(function () {
      var eleIndex = stores.indexOf({ "store_id": parseInt($('#market' + index).val(), 10) });
      if (index !== -1) {
        stores.splice(eleIndex, 1);
        oldValue.splice(eleIndex);
      }
      $(this).closest("div").remove();

    });
  });


});

下面的代码也总是输出-1,所以我认为 indexOf 没有意义。

var eleIndex = stores.indexOf({"store_id": parseInt($('#market' + index).val(), 10)});

编辑:我按照要求用 HTML 部分更新了帖子。简而言之:当点击 button(#add) 时,会克隆 div(#form),将添加删除按钮,并使用索引更新 id。 所有这些选择的值都将存储并更新在 stores 数组中。我只是无法删除它们。

我还提供了一个有效的 jsfiddel https://jsfiddle.net/proach1995/h1gtmyen/

【问题讨论】:

  • 欢迎来到 StackOverflow。你能添加你正在使用的 HTML 代码的骨架吗?我试图想象你在做什么。
  • 感谢@DanNagle 我提供了一个 jsfiddle 来明确我想要归档的内容

标签: javascript jquery arrays


【解决方案1】:

使用纯 js,您可以将类添加到您希望从中收集的下拉列表中。在下面的代码中,只有在选择值时才会构建数组。 如果您使用 jQuery,您可以将 document.querySelectorAll('.store'); 替换为 $('.store');

function saveArray() {
  const selected = document.querySelectorAll('.store');
  const stores = [];
  selected.forEach(prop => {
    if (!!prop.value) {
      stores.push({store_id: parseInt(prop.value, 10)})
    }
  });
  console.log(stores);
}
<select class="store">
  <option disabled selected value>select value</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<select class="store">
  <option disabled selected value>select value</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
</select>
<select class="store">
  <option disabled selected value>select value</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>
<button onclick="saveArray()">save array</button>

【讨论】:

  • 感谢您的建议。在我的情况下,输入字段是动态添加的,所以我认为我无法以正确的方式应用您的答案。我在原始帖子中添加了一个 jsfiddle 以明确我想要做什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多