Home > Blockchain >  How to map inputs inside each div to create array of hash using Javascript
How to map inputs inside each div to create array of hash using Javascript

Time:01-28

I have HTML as below

<div >
  <div >
    <input type="text" name="description" id="description"  placeholder="For example, Youtube Link">
    <input type="text" name="link" id="link"  placeholder="For example, https://www.youtube.com/">
  </div>

  <div >
    <input type="text" name="description" id="description"  placeholder="For example, Youtube Link">
    <input type="text" name="link" id="link"  placeholder="For example, https://www.youtube.com/">
  </div>
</div>

I have tried to iterate over each assets-form and create object like below

[
  {
    "link": "http://google.com/one",
    "description": "Link One"
  },
  {
    "link": "http://google.com/two",
    "description": "Link Two"
  }
]

using below function

$.map($('.assets-form'), function(field) {
  console.log(field)
});

Here I'm not able to construct the hash after looping over each div

CodePudding user response:

you can launch the map function after form have been complete

in my sample i add a button to have to be click after input have been filled you can recover field value by $(field).find({fieldSelector})

function mapField() {
  let links = [];
  links = $.map($('.assets-form'), function(field) {
    return {
      link:$(field).find('#link').val(),
      description:$(field).find('#description').val(),
    }
  });

  console.log(links);
}
<div >
  <div >
    <input type="text" name="description" id="description"  placeholder="For example, Youtube Link">
    <input type="text" name="link" id="link"  placeholder="For example, https://www.youtube.com/">
  </div>

  <div >
    <input type="text" name="description" id="description"  placeholder="For example, Youtube Link">
    <input type="text" name="link" id="link"  placeholder="For example, https://www.youtube.com/">
  </div>
</div>
<button onclick="mapField()">map field</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP u1T9qYdvdihz0PPSiiqn/ /3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  •  Tags:  
  • Related