Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the value of an option in select menu onChange using jquery?

I'm trying to implement clone select menu using the ScrollectBox plugin:

https://github.com/afEkenholm/ScrollectBox/blob/master/index.html

https://github.com/afEkenholm/ScrollectBox/blob/master/js/ScrollectBox/jquery.scrollectbox.js

but I'm unable to get the option value of the select menu. It returns the option text instead.

How to get the value (but not text) of an option in the following select menu onChange using jQuery call function?

<script type="text/javascript">
jQuery(document).ready(function($){ 
   $(".selection").scrollectBox({
    preset: 'dropdown',
    numVisibleOptions: 4,
    scrollInterval: 150, 
    scrollOn: 'hover'
    });
});
</script>

    <select onchange="function(this);" id="selector" class="selection" >
    <option value="" selected="Select Topic">Select Topic</option> 
    <option value="Food">Food</option>
    <option value="Drink">Drink</option>
    </select>

Doesn't work

<script type="text/javascript">
jQuery(document).ready(function($){ 
   var selectEvent = function($el){
someFunction($(this).val());
return false;
};
   $(".selection").scrollectBox({
    preset: 'dropdown',
    numVisibleOptions: 4,
    onSelectEvent: selectEvent,
    scrollInterval: 150, 
    scrollOn: 'hover'
    });
});
</script>

it returns [object Object]

Doesn't work

    <script type="text/javascript">
jQuery(document).ready(function($){ 
    $(".selection").scrollectBox({
        preset: 'dropdown',
        numVisibleOptions: 4,
        scrollInterval: 150, 
        scrollOn: 'hover',
        onSelectEvent: function (item, event) {
           alert(item).val();
        }
    });
});
</script>

it returns [object Object]

like image 612
Klanto Aguntuk Avatar asked Jan 14 '23 21:01

Klanto Aguntuk


2 Answers

According to the source code for ScrollectBox, you must use the onSelectEvent property, like so:

jQuery(document).ready(function($){ 
    $(".selection").scrollectBox({
        preset: 'dropdown',
        numVisibleOptions: 4,
        scrollInterval: 150, 
        scrollOn: 'hover',
        onSelectEvent: function (item, event) {
           alert(item.val());
        }
    });
});
like image 155
mattytommo Avatar answered Jan 19 '23 10:01

mattytommo


You can refer to the selected option via: $("#selector option:selected")

$("#selector").change(function() {
   var selectedValue = $("#selector option:selected").val();
   alert('Selected value ' + selectedValue);
});

JS Fiddle: http://jsfiddle.net/Y7byM/1/

Edit:

From your comments you can change #selector to .selector:

$(".selection").change(function() {
   var selectedValue = $(".selector option:selected").val();
   alert('Selected value ' + selectedValue);
});
like image 20
Darren Avatar answered Jan 19 '23 11:01

Darren