How can I have jQuery code further optimized? I would like to see if my code below can still be optimized, resulting in lesser lines of code. My code retrieves the values from a multiselect field and assign them to hidden fields that will be passed to an integrated googlesheet. Thanks
 jQuery(&quot;.ff-btn-submit&quot;).click(function() {
        if(jQuery(&quot;input:radio[name=gift_choice]&quot;).is(&quot;:checked&quot;) ) {
            if (jQuery(&quot;input[name=gift_choice]:checked&quot;).val() == 'yes') {
                // Retrieve multi-select values
                var selectedValues = [];
                selectedValues = $('#ff_124_multi_select_gifts').val();
                
                // Set hidden input with the chosen gift.
                if (selectedValues.length &gt; 0) {
                  jQuery(&quot;input[name=gift_1]&quot;).val(selectedValues[0]);
                  jQuery(&quot;input[name=gift_2]&quot;).val(selectedValues[1]);
                  jQuery(&quot;input[name=gift_3]&quot;).val(selectedValues[2]);
                  jQuery(&quot;input[name=gift_4]&quot;).val(selectedValues[3]);
                  jQuery(&quot;input[name=gift_5]&quot;).val(selectedValues[4]);
                  jQuery(&quot;input[name=gift_6]&quot;).val(selectedValues[5]);
                } 
            }
        }
    });
I have few hints save jQuery in $ variable:
(function($) {
   // your code
})(jQuery);

$ is common for jQuery and it's easier to read because it shorter.
Second and obvious is using loop to run calls in:
    if (selectedValues.length &gt; 0) {
       selectedValues.forEach(function(value, i) {
          var num = i + 1;
          $(`input[name=gift_${num}]`).val(value);
       });
    }

and further improvement is to move that into a function. So instead of comment:
// Set hidden input with the chosen gift.

you can have:
setHiddenInputs(selectedValues);


function setHiddenInputs(values) {
    values.forEach(function(value, i) {
        var num = i + 1;
        $(`input[name=gift_${num}]`).val(value);
    });
}

I would also merge those two lines:
var selectedValues = [];
selectedValues = $('#ff_124_multi_select_gifts').val();

you assign array for no reason and then replace it with output of val() call:
var selectedValues = $('#ff_124_multi_select_gifts').val();

also if selectedValues are gifts then you can use:
var selectedGifts = $('#ff_124_multi_select_gifts').val();
setHiddenInputs(selectedGifts);

which is exactly what your comment try to say