Question

I am trying to use split on a multiple selection dropdown menu and it is returning an error of: "Uncaught TypeError: Object f-all has no method 'split'". Is it not possible to use split on a multi select?

Here is the dropdown (simplified):

<select data-placeholder="Select" placeholder="Select" name="id[]" id="id_menu" multiple>
    <option value=""></option>
    <option value="e-all">E All</option>
    <option value="f-all">F All</option>
</select>

And here is the split function:

$('#id_menu').change(function(){
    var id_menu = $(this).val();
    var type = id_menu.split('-');
    // do stuff with split id
 });

Tried with an each an still same error message

$('#id_menu').change(function(){
     $('#id_menu').each(function() {
         var type = $(this).val().split(',');
     });
});

Thanks in advance.

Was it helpful?

Solution

$(function(){

    $('select').change(function(){

       //typeof $(this).val() === 'Array'

        $.each($(this).val(), function(i, val){ 
            console.log(val); //handle each selected value
        });
    });

});​

OTHER TIPS

As you are using multiple attribute, val returns an array of selected values, that has no split method, you can use join method for converting the array to a string or loop through the array.

$('#id_menu').change(function(){
    var id_menu = $(this).val().join();
    // var id_menu = $(this).val();
    // for (var i = 0; i < id_menu.length; i++) {
    //      var sin = id_menu[i].split('-');
           // ..
    // }
});

id_menu is an array

$('#id_menu').change(function() {
  var id_menu = $(this).val();
  //id_menu is an array
  id_menu.forEach(function(item, index) {
    var split_item  = item.split('-');
  });
});

To get the selected values, you could also do something like this:

 $('#id_menu').change(function (e) {
    $(e.currentTarget).val();
 });

Here is a demo: http://jsfiddle.net/7HVPH/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top