Jarla Jarla - 24 days ago 6
jQuery Question

How can create divs on option change?

I want to create divs with the class "colors" by option change. It works well, but anytime I change the option, more and more divs are created. But I have only two "colors", so as a result anytime I change the option, I only want to see two divs: "blue" and "red". I tried to used

$('.result').remove();
before appending. But then nothing is appended...



$(document).ready(function() {
$("#select").on("change", function() {
$(".colors").each(function() {
var color = $(this).attr('title');
$(".result").append("<div>" + color + "</div>");
});
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="select">
<option class="colors" title="blue">a</option>
<option class="colors" title="red">b</option>
<option title="green">c</option>
</select>

<div class="result"></div>




Answer

To do what you require you can simply call empty() on the .result div before you loop through and create the new div elements. Try this:

$(document).ready(function() {
  $("#select").on("change", function() {
    $('.result').empty();
    
    $(".colors").each(function() {
      $(".result").append("<div>" + this.title + "</div>");
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="select">
  <option class="colors" title="blue">a</option>
  <option class="colors" title="red">b</option>
  <option title="green">c</option>
</select>

<div class="result"></div>

Comments