skip to Main Content

I have some inputs in my HTML like:

  <input type="text" name="offer-add[lname][]" class="form-control offer-input" id="offer-add-lname" placeholder="">
  <input type="text" name="offer-add[fname][]" class="form-control offer-input" id="offer-add-fname" placeholder="">

I want get all the values in JS as an array, but as array key I want e.g. lname, fname.

I tried with:

  var values = $("input[name^='offer-add']")
    .map(function(){return $(this).val();}).get();

so got as key only numbers (0, 1, 2, …).

2

Answers


  1. If you want the input’s value and part of id as an object on a button click then try the following way:

    $('#getData').click(function(){
      var values = $("input[name^='offer-add']")
        .map(function(){
          return {
            'key': $(this).attr('id').split('-').slice(-1)[0] ,
            'value': $(this).val()
            };
        }).get();
    
      console.log(values);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" name="offer-add[lname][]" class="form-control offer-input" id="offer-add-lname" placeholder="">
    <input type="text" name="offer-add[fname][]" class="form-control offer-input" id="offer-add-fname" placeholder="">
    
    <button id="getData">Click</button>
    Login or Signup to reply.
  2. Get the inputs, extract the name and value, and then extract the necessary part of the name using a regex. Finally, convert the key/value pairs into an object.

    function go() {
    
      let obj = Object.fromEntries(
        [...document.querySelectorAll(`input[name^='offer-add']`)]
        .map(e=>[/[(?<key>[^]]+)]/.exec(e.name).groups.key, e.value]));
    
      console.log(obj);
    
    }
    <input type="text" name="offer-add[lname][]" class="form-control offer-input" id="offer-add-lname" placeholder="">
    <input type="text" name="offer-add[fname][]" class="form-control offer-input" id="offer-add-fname" placeholder="">
    <button onclick="go()">Go</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search