0

I have a small form with three fields and I can submit that form choose different options next time. I am submitting this form with ajax call.

Now on form submit I want to post all the selected options. For this, I have created a hidden field like

<input type="hidden" name="selectedproduct[]" id="sel-product">

and ajax success method am appending value like

 $('#sel-product').val(element.product);

But here I am getting only one value instead of an array. How can I append all the values to the field?

4
  • Where did you get the element.product object? can you show us the structure of the element data. Commented Jul 2, 2018 at 9:17
  • in ajax response $(data.success).each(function( index, element ) {$('#sel-product').val(element.product);}); Commented Jul 2, 2018 at 9:18
  • That won't work. The input element will just be filled with the value of the last element of your array. You need to push the element.product in a temporary array variable then put the temp array on the input value. Commented Jul 2, 2018 at 9:27
  • But when I send ajax call again temp array getting reset and I have only one value :( Commented Jul 2, 2018 at 10:16

1 Answer 1

2

Assuming the product fields with class ".element_product".

//init the array products
arrp=[];


//loop the elements
    $('.element_product').each( function () 
      {
            arrp.push( $(this).val() );
      });

//Pass the array to field
$('#sel-product').val(arrp);
Sign up to request clarification or add additional context in comments.

5 Comments

You don't close your each loop
it still overwriting previous values
Store the previous values in an array and push arrp to array with previous values. Join them in input.
It still not working. Could you please whats wrong here [arrp=[] temp =[]; temp = element. product; $('.selectedMet').each( function () { arrp.push(temp); }); $('#sel-product').val(arrp);]
You are looping element.product (as temp) in the array without passing the values of inputs

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.