1

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?

3
  • Try input[name^=tests]. w3schools.com/cssref/sel_attr_begin.asp Commented Dec 10, 2021 at 15:40
  • @RatajS thanks i can retrieve the value, but how can i also retrieve the predefined array key? Commented Dec 10, 2021 at 15:47
  • I edited my code below Commented Dec 10, 2021 at 16:30

1 Answer 1

1

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">

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

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.