Daniel Ellison
Daniel Ellison

Reputation: 1349

How to properly append on change of a select

I have a very simple select input that allows multiple choice. What I'm trying to do is simply display in the PRE the selected choice(s) into spans. It seems to be working fine when it comes to single selections but not when selecting multiple choices.

For example if I select multiple choices, in my PRE it only displays 1 item instead of an array.

Script: https://jsfiddle.net/

$('#selectpicker').on('change', function(){
    var test = $('#selectpicker').val();
    $.each(test, function (value) {
    $('#pre_support').html("");
    $('#pre_support').append("<span class='btn btn-primary btn-xs'>"+this+"</span>");
    });
});

Would anyone have any ideas?

Upvotes: 1

Views: 61

Answers (3)

Prakash
Prakash

Reputation: 576

Hope this helps you and believe that you are looking for this

$(document).ready(function() {
  $('#selectpicker').on('change', function() {
    $('#pre_support').html("");
    var test = $('#selectpicker').val();
    $.each(test, function(value) {
      $('#pre_support').append("<span class='btn btn-primary btn-xs'>" + this + "</span>");
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="selectpicker">
  <option value="1">Test 1</option>
  <option value="2">Test 2</option>
  <option value="3">Test 3</option>
  <option value="4">Test 4</option>
  <option value="5">Test 5</option>
  <option value="6">Test 6</option>
</select>
<span id="pre_support"></span>

Upvotes: 1

Nirav Kamani
Nirav Kamani

Reputation: 3272

Here is your correction please check it once.

$('#selectpicker').on('change', function(){

    var test = $('#selectpicker').val();

    $('#pre_support').html("");

    $.each(test, function (value) {
        $('#pre_support').append("<span class='btn btn-primary btn-xs'>"+this+"</span>");
    });
});

Here is Fiddle Demo you can check it.

Your mistake is you cleared html in every iteration.

Upvotes: 1

Shyju
Shyju

Reputation: 218702

Because you are clearing the innerHtml of pre_support it in every iteration of the $.each loop. So it is going to overwrite the content you set to "".

Move it outside of the loop.

$('#pre_support').html(""); 
$.each(test, function (value) {       
    $('#pre_support').append("<span class='btn btn-primary btn-xs'>"+this+"</span>");
});

Upvotes: 3

Related Questions