Home > Software design >  Unable to push to id to JavaScript array along with values
Unable to push to id to JavaScript array along with values

Time:09-22

I have written code to create a dynamic array to loop through all controls inside a div and frame an array, not sure what is wrong but unable to push id to array. When I log it to console I can see the Id

$('#btnClick').click(function() {
  saveDiv($("#div1"))
});

function saveDiv(div) {
  var controlValues = [];
  div.find('input:text, input:password, input:file, select, textarea')
    .each(function() {
      //console.log($(this).attr("id"));
      var id = $(this).attr("id");
      var quote_str = "'"   id   "'";
      console.log(id);
      controlValues.push({
        quote_str: $(this).val()
      });
      console.log(controlValues);
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
  <div id="div1">
    <div class="row g-3">
      <div class="col-sm-6">
        <label for="vesselname" class="form-label">Vessel Name</label>
        <input type="text" class="form-control" id="vesselname" placeholder="Enter Vessel Name" value="">
      </div><br />
      <div class="col-sm-6">
        <label for="vesseltype" class="form-label">Vessel Type</label>
        <select class="form-select" id="vesseltype">
          <option>--Select--</option>
          <option>Test</option>
        </select>
      </div><br />
      <div class="form-check mb-2">
        <input class="form-check-input" type="checkbox" value="" id="formCheck5">
        <label class="form-check-label" for="formCheck5">Material Damage</label>
      </div>
      <br>
      <button id="btnClick">Click me</button>
    </div>
  </div>
</div>

Instead of Id I am always getting the id as quote_str

CodePudding user response:

Update: Based on OP's comment, you want to have the dynamic key as id variable, which you can do by putting the var inside square brackets as [id]

controlValues.push({
  [id]: $(this).val(),
});

WORKING CODE BELOW

  • Related