jqueryarraysformsmultidimensional-arraysubmission

how get input value of form in associative array with jQuery


There is a form with list wrapper with input tag inside which they are created dynamically.

<div class="wrapper">
  <div class="action-elements cross-icon"> X </div>
  <input name="term-title" type="text" value="blue" class="action-elements term-title" id="term-title">
  <div class="action-elements term-quantity-price">
    <input name="color_quantity" class="color_quantity" id="color_quantity" type="number" placeholder="Quantity">
    <input name="color_price" class="color_price" id="color_price" type="number" placeholder="Price">
  </div>
</div>

<div class="wrapper">
  <div class="action-elements cross-icon"> X </div>
  <input name="term-title" type="text" value="red" class="action-elements term-title" id="term-title">
  <div class="action-elements term-quantity-price">
    <input name="color_quantity" class="color_quantity" id="color_quantity" type="number" placeholder="Quantity">
    <input name="color_price" class="color_price" id="color_price" type="number" placeholder="Price">
  </div>
</div>

How can I get input in multidimensional array when submit form. something like this

array{1:array{term-title:blue, color_quantity:10, color_price:200}, 2:array{term-title:red, color_quantity:20, color_price:30},...}

Solution

  • is the wrapper inside a form tag ? if so please checkout serializeArray().

    in general if you want to get all the data in the form you can use serialize() or serializeArray().

    here is an example:

    $("form").submit(function(event) {
      event.preventDefault();
      console.log($(this).serializeArray());
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form>
      <div class="wrapper">
        <div class="action-elements cross-icon"> X </div>
        <input name="term-title" type="text" value="blue" class="action-elements term-title" id="term-title">
        <div class="action-elements term-quantity-price">
          <input name="color_quantity" class="color_quantity" id="color_quantity" type="number" placeholder="Quantity">
          <input name="color_price" class="color_price" id="color_price" type="number" placeholder="Price">
        </div>
      </div>
    
      <div class="wrapper">
        <div class="action-elements cross-icon"> X </div>
        <input name="term-title" type="text" value="red" class="action-elements term-title" id="term-title">
        <div class="action-elements term-quantity-price">
          <input name="color_quantity" class="color_quantity" id="color_quantity" type="number" placeholder="Quantity">
          <input name="color_price" class="color_price" id="color_price" type="number" placeholder="Price">
        </div>
      </div>
      <input type="submit" />
    </form>