Dustin Dustin - 3 months ago 23
Javascript Question

Add array values to hidden form field

I am trying to add comma separated values to a hidden form field for later processing using the change of a dropdown menu as my trigger.



$("#artistselect").change(function() {
var allids = [];

allids.push($(this).children(":selected").attr("id"));

$("input[name=artistslist]").attr("value", $(allids).append(allids + ", "));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="artistselect">
<option value="1">1</option>
<option value="1">1</option>
<option value="1">1</option>
</select>
<input type="hidden" name="artistslist" value="" />
</form>





Best I can manage is to get the value to change to the selected dropdown, but it wont add them together with the commas.

Answer

Move var allids=[]; out of the event because you're destroying it every time it fires.

var allids=[];

$("#artistselect").change(function() {
    allids.push($(this).children(":selected").attr("id"));

     $("input[name=artistslist]").val(allids.join(', '));
});

On the last line you can use Array.prototype.join to get a comma separated string from the array.

Not sure why you are using .attr("id") when your html shows your options with no id attribute. Looks like you want value not id.