3

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.

2
  • Didn't understand what actually you want Commented May 14, 2016 at 13:14
  • 1
    If you use $("form").serialize() jQuery will do this automatically for you. Commented May 14, 2016 at 13:34

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

2

You can use Attribute Starts With Selector

 $( "input[name^='bike']" );

See JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.