Doctore Doctore - 6 months ago 6
Javascript Question

How to get all values from inputs with same name but different index via Jquery

I had a task and now this is kind weird and I don't know, how to do that. So, I have non-specific number of inputs, with same name

car
but different indexes, like
sub
,
master
and
val
.

It looks like this:



<input type='text' name='bike[master]' value='some predefined value 1'>
<input type='text' name='bike[sub]' value='some predefined value 2'>
<input type='text' name='bike[val]' value='some predefined value 2.1'>
<input type='text' name='bike[sub]' value='some predefined value 3'>
<input type='text' name='bike[val]' value='some predefined value 3.1'>





I need, that jQuery, after user click on input, take all these values from inputs to one variable, if it will be possible, and send to server, which will put these data together and work with them.

Any idea? It is little bit complicated with indexes for me.

Answer

You can take values of each input which name starts with bike on click and push it in one array

var result = [];
$('button').click(function() {
  $('input[name^="bike"]').each(function() {
    result.push($(this).val());
  })
  console.log(result)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' name='bike[master]' value='some predefined value 1'>
<input type='text' name='bike[sub]' value='some predefined value 2'>
<input type='text' name='bike[val]' value='some predefined value 2.1'>
<input type='text' name='bike[sub]' value='some predefined value 3'>
<input type='text' name='bike[val]' value='some predefined value 3.1'>
<button>Send</button>

You can also use JQuery serializeArray() function and return array, and then use that data

$('form').click(function() {
  var data = $(this).serializeArray();
  data.forEach((e) => {console.log(e.value)});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
  <input type='text' name='bike[master]' value='some predefined value 1'>
  <input type='text' name='bike[sub]' value='some predefined value 2'>
  <input type='text' name='bike[val]' value='some predefined value 2.1'>
  <input type='text' name='bike[sub]' value='some predefined value 3'>
  <input type='text' name='bike[val]' value='some predefined value 3.1'>
  <input type="submit" value="Send">
</form>

Comments