Reputation: 1242
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.
Upvotes: 1
Views: 6933
Reputation: 144719
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('-');
// ..
// }
});
Upvotes: 2
Reputation: 40491
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/
Upvotes: 0
Reputation: 7096
$('#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('-');
});
});
Upvotes: 1
Reputation: 35213
$(function(){
$('select').change(function(){
//typeof $(this).val() === 'Array'
$.each($(this).val(), function(i, val){
console.log(val); //handle each selected value
});
});
});
Upvotes: 4