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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With