-2

Below is the code to populate hidden fields in my form based on the number of items present in an multi choice field. I find it difficult to create gift_1, gift_2, which is where I need your help. Thanks

    if (selectedValues.length > 0) {
        for (var i = 0; i < selectedValues.length; i++) {
          jQuery("input[name=gift_1]").val(selectedValues[i]);
        }
    } 
4
  • You mean you want something like jQuery(`input[name='gift_${i}']`)? Starting from 0 or from 1? Commented Mar 21, 2021 at 17:23
  • Yes, but that should start with 1 not 0 that i holds. Commented Mar 21, 2021 at 17:24
  • 2
    @CodeForGood Add one. Commented Mar 21, 2021 at 17:27
  • This entire code (with corrected semantics) can be replaced by selectedValues.forEach((val, index) => document.querySelector(`input[name='gift_${index + 1}']`).value = val); Commented Mar 21, 2021 at 17:37

1 Answer 1

1

concatenate using "input[name=gift_" + (i+1) + "]"

or use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

jQuery(`input[name=gift_${i+1}]`)

if (selectedValues.length > 0) {
    for (var i = 0; i < selectedValues.length; i++) {
      jQuery(`input[name=gift_${i+1}]`).val(selectedValues[i]);
    }
} 
Sign up to request clarification or add additional context in comments.

7 Comments

Does this give gift_1 or gift_0 in the first iteration? thanks
@CodeForGood as we are using i+1 it will give gift_1
@CodeForGood If you start with var i = 0;, what is i + 1?
I want to get gift_1 in the first iteration and gift_2 in the second iteration as long the as the array has the elements
@CodeForGood Using logic, what do you believe it does?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.