1
votes

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.

3
say first i am selecting key1 in dropdown A, so value1 and value2 are populated in the dropdown B, if i select key2, then value3 and value4 are appended to the already existing values.Parameswar
It's much better to put the code with 4 indents ` ` than to put an image of the code that cannot be easily copied here. You want to .remove() the children first, .replaceWith() or .html() for jquery.Francisco Presencia
since i was running short of time,instead of formating the code,thought pasting the image ,thanks a lot FranciscoParameswar
One thing to point out: you're only using jQuery for a single .ready() statement, but with your script at the end of the body, you can actually remove lines, "$( document ).ready(function() {" and it's closing, "})". Then you'll be running completely native :) and can drop some dead weight and remove your jQuery <script> reference all together.kmatheny

3 Answers

1
votes

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.

0
votes

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.
  });
0
votes

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);