Mujo M Mujo M - 25 days ago 8
jQuery Question

Call for a specific array to populate <select> drop down on radio button click

I have found a way to populate a drop down list with a particular array on a specific radio button click... such as in my example when you click colors. It will display that array or when you click products it will display that array. But I need help getting rid of of let's say the colors array when I call for the products array, or get rid of the products array when I call for the colors array. So basically un-append one array when I call for the other.

var productsArray = ['Cookies', 'Milk', 'Soda'];
var colorsArray = ['Blue', 'Green', 'Red'];

if($(this).val() === 'products'){
for(var i = 0; i < productsArray.length; i++) {
$('#dropdown2').append('<option value='+i+'>'+productsArray[i]+'</option>');
else if ($(this).val() === 'colors'){
for(var i = 0; i < colorsArray.length; i++) {
$('#dropdown2').append('<option value='+i+'>'+colorsArray[i]+'</option>');

<script src=""></script>
<form class="" action="index.html" method="post" id="form2">
<label for="productsRadio">Products</label>
<input type="radio" name="radioSelection" value="products">
<label for="colorsRadio">Colors</label>
<input type="radio" name="radioSelection" value="colors">
<select class="" name="" id="dropdown2">

Here is a js-fiddle example... as you can see when you select the colors radio button and then select the products radio button the dropdown gets filled with both arrays. But I want it to be filled with one array at a time. I want the colors array when the color radio button is selected and then when I want the products array I want the color array to be cleared and for the products array to show up. Hope that makes sense!

Answer Source

You're almost there, the problem is that it just appends because that's all you're telling the script to do. You're only making it add stuff, you need to also remove stuff.

Try this