Parameswar
Parameswar

Reputation: 2069

create a new drop down based on another drop down in javascript

Here is my requirement.

List item

  1. I have a couple of dropdowns A and B
  2. I have a javascript key-value variable created:
  3. var keyvalue={"key1":["value1","value2"],"key2":["value2","value4"]}

  4. I am populating the keys in dropdown A, on selecting this dropdown, i am populating the corresponding values (froom the keyvalue variable) into the drop down B

Here is the sample code i a using :enter image description here

The problem is even if i select a different option in dropdown A, the corresponding old option is present in the new drop down,i.e, new values are appended, rather than creating a new drop down Any help is appreciated,thanks in advance.

Upvotes: 1

Views: 994

Answers (3)

kmatheny
kmatheny

Reputation: 4202

You need to remove all options before populating. Add this directly right after your var quantity statement.

while (selectvalue.options.length > 0) {
    selectvalue.remove();
}

Also, as mentioned by @francisco-presencia, you should lose the onchange in the HTML and instead use an event listener within your script.

Upvotes: 1

Gary Hayes
Gary Hayes

Reputation: 1788

You should use empty() to remove the old options before appending the new.

You can see it on my sample Fiddle:

JS Fiddle Here

$('#select2').empty().append(Weapons);

Upvotes: 0

Francisco Presencia
Francisco Presencia

Reputation: 8851

I recommend you go the separation of concerns route. That means deleting the onclick="" event, and instead doing:

$('#key').change(function(){
  $('#value').remove();
  // Do the rest of the logic of retrievevalue() here.
  });

Upvotes: 0

Related Questions