Home > other >  jQuery: Get value from input array with predefined array key
jQuery: Get value from input array with predefined array key

Time:12-11

I have an html input array with predefined array key (the predefined key is needed for further action) like this:

<input type="hidden" name="tests[5]" value="b">
<input type="hidden" name="tests[8]" value="a">

i tried to get the value using a jQuery method like this:

var testsValues = $('input[name="tests[]"]').map(function () {
                return this.value; // $(this).val()
           }).get();

console.log(testsValues);

it always gives an empty result, but if i remove the predefined key it will not give an empty result

<input type="hidden" name="tests[]" value="b">
<input type="hidden" name="tests[]" value="a">

what is the right way to retrieve the input array values with the predefined key?

CodePudding user response:

You can use better selector like $('input[name^="tests"]') to get elements names starting by tests and then loop them with each.

EDIT : to get the key, you can use split the name with separator "[" of the input to get second element [1] and then replace last element to make it clean "]".

https://api.jquery.com/each/

https://api.jquery.com/category/selectors/

$('input[name^="tests"]').each(function() {
  let inputName = $(this).attr("name");
  let inputKey = inputName.split('[')[1].replace(']', '');
  let inputVal = $(this).val();
  console.log("Name : "   inputName   " - Key : "   inputKey   " - "   " Value : "   inputVal);
  
  if (inputKey == 5) {
    // do something
    console.log("Key is egal to 5 - Value : "   inputVal);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="tests[5]" value="b">
<input type="hidden" name="tests[8]" value="a">

  • Related