Anna Jeanine
Anna Jeanine

Reputation: 4125

Get selected value from multiple select on change in dynamic form

I'm currently working on a dynamic form which enables the user to add as many variants as they would like. This form which can be added has a price, size and color. The size and color are select2 select boxes which enable the user to select multiple things. The form:

<div class="col-sm-4">
   <label>Kleuren</label>
   <select name="colors[{{$i}}][]" id='color-options' class="form-control multiple-select" multiple="multiple">
   @foreach($colors as $id=>$color)
      <option value="{{$id}}">{{$color}}</option>
   @endforeach
   </select>
</div>

When looking at the HTML code I have multiple of these forms which go by name: colors[0][], colors[1][], colors[2][] etc.

How do I print the value of a selected new color in a new div? The code which I have thus far:

    $(document).ready(function() {
        $('.multiple-select').select2({
            language: 'nl'
        });
        $('.summernote').summernote();

        var addVariantButton = document.getElementById('addVariant[0]');
        addVariantButton.addEventListener('click', function(){
            addVariant(0);
        });

        var colorSelected = document.getElementsByName('colors[0][]');
        colorSelected.addEventListener("click", displayColorSelected);
    });

    function displayColorSelected() {
        var selected_value = document.getElementById("color-options").value;
        console.log(selected_value);
    } 

But this only works for the first colors input form, but how can I make this into a more dynamical function to get all colors input?

Upvotes: 1

Views: 3128

Answers (3)

LegenJerry
LegenJerry

Reputation: 414

You may need to delegate your event listener

 document.addEventListener('event',function(e){
    if(element){//do something}
 })

Since you are using jquery its easier

$(document).on('event','element',function());

Upvotes: 1

Karan
Karan

Reputation: 12619

You can get all selected values in array as below:

function displayColorSelected() {
    var selected_value = $("[id='color-options']").toArray().map(x => $(x).val());
    console.log(selected_value);
}

Note: id selector will always return single element which will be first with that id. So you're getting value for first select only.

You can use attribute selector ([]) instead which will find every element with given id. So here $("[id='color-options']").toArray() will find every element with id equal to color-options and map(x => $(x).val()) will return only value part from the elements array.

Upvotes: 1

Programmer
Programmer

Reputation: 2123

Add all the selects a class ("color-select" for example), and run over all the selects -

$('.color-select').each(function() { console.log($(this).val()); })

Upvotes: 1

Related Questions