joshuadelange
joshuadelange

Reputation: 390

Semantic UI: Dynamically added dropdown menu doesn't change value in select

While using the Semantic UI framework, I'm working on a form where multiple items can be dynamically added.

In the form of these items is a dropdown menu that I need to listen for changes to. This works perfectly for the drop downs that were initialised when the page loaded, but not for the drop downs that were added dynamically.

In attempt to isolate my problem, I created this JSFiddle: https://jsfiddle.net/e7q1shyv/1/

It seems that the Semantic UI dropdown menu is not updating the <select>.

I've tried looking in the documentation and searched around but was not able to find anything about this.

Thank you for any ideas you may have on fixing this problem!

Upvotes: 0

Views: 1943

Answers (3)

codeslayer1
codeslayer1

Reputation: 3686

You have an error in this line.

$(document).on('change', 'select', function(){
    $('span').html($('select').val())
});

Here you are taking the value of 'select' which will always correspond to first select element in your selects class. Change it to $this to get current instance value.

Your code would change to

$(document).on('change', 'select', function(){
    $('span').html($(this).val())
});

Working fiddle - https://jsfiddle.net/e7q1shyv/3/

Upvotes: 1

SilverSurfer
SilverSurfer

Reputation: 4368

Just change $('select') for $(this), like following, and it works perfect:

$(document).on('change', 'select', function(){
    $('span').html($(this).val())
});

Upvotes: 1

Rahul
Rahul

Reputation: 18557

Checking working code.

$(document).ready(function() {
  $('select').dropdown();
});

$(document).on('change', 'select', function() {
  var valu = $(this).val();
  $('span').html(valu);
});

$('button').click(function() {
  $('select').first().clone().appendTo('.selects')
  $('select').dropdown();
});
.ui.button {
  margin-top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.1/semantic.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.1/semantic.js"></script>
<div class="selects">
  <select class="ui dropdown">
    <option>Option 1</option>
    <option>Option 2</option>
  </select>
</div>

<button class="ui button">Add select</button>

<p>Value changed: <span></span></p>

What you were doing is fetching value of only select element, so it will every time fetches value of first instance of select in dom.

If you give current element's value as I wrote var valu = $(this).val(); it will fetch current element's value.

Here is your updated jsfiddle link.

Upvotes: 1

Related Questions