Home > Net >  how to pass values from multiple textfields with same name attributes to a variable in form of an ar
how to pass values from multiple textfields with same name attributes to a variable in form of an ar

Time:02-13

I am building a form that passes a set of numbers in form of an array to a variable as seen below

  var users=["1","2"];

the main purpose of this is to then make an Ajax request with these numbers and get their corresponding content in my database which I then pass to their respective divs, please see below

 var users=["1","2"];
   
var async_request=[];
var responses=[];
for(i in users)
{
    // you can push  any aysnc method handler
    async_request.push($.ajax({
        url:'back.php', // your url
        method:'post', // method GET or POST
        data:{user_name: users[i]},
        success: function(data){
            console.log('success of ajax response')
            responses.push(data);
          
        }
    }));
}


$.when.apply(null, async_request).done( function(){
    // all done
    console.log('all request completed')
    console.log(responses);
      $( '#responses' ).html(responses[1]);
      $( '#responses1' ).html(responses[0]);
       
});

This works perfectly.

But now I want to make some adjustments to my solution specifically

Im looking to replace the method of passing the numbers to the variable users

from

  var users=["1","2"];   // Im looking to replace the method

to this

var users = $('[name="tom[]"]').val(attachArray);

 <input type="text" name="tom[]" value="1" /><br>
        <input type="text" name="tom[]" value="2" /><br>

but I am unable to get the the ids from the two textfields and then pass to my database using my Ajax script as I did before with this

  var users=["1","2"]; 

CodePudding user response:

You mean

const arr = ["1", "2"]
$('[name^=tom]').val(function(i) {
  return arr[i]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tom[]" value="" /><br>
<input type="text" name="tom[]" value="" /><br>

CodePudding user response:

You forgot to use input key value :

var users = $('input[name="tom[]"]').val();
  • Related