Sebastian Sebastian - 4 months ago 55
Javascript Question

Get value of selected <option> in ddSlick dropdown

This currently returns undefined. What should go in the commented line to alert the value (1, 2, 3 or 4) of the current

<option>
tag?

<select id="dropdown" name="dropdown">
<option value="0" data-imagesrc="images/icons/all.png">All Questions</option>
<option value="1" id="friends" data-imagesrc="images/icons/friends.png">Friends</option>
<option value="2" data-imagesrc="images/icons/friends_of_friends.png">Friends of Friends</option>
<option value="3" data-imagesrc="images/icons/network.png"><?php echo $network; ?></option>
<option value="4" data-imagesrc="images/icons/location.png"><?php echo $location ?></option>
</select>

<script type="text/javascript">
$('#dropdown').ddslick({
showSelectedHTML: false,
onSelected: function(selectedData){
var str = $(this).attr('id'); // WHAT SHOULD GO HERE?
alert(str);
}
});
</script>


EDIT

If it's relevant, I'm using this plugin.

Perhaps this question might help. I'm trying to make sense of it.

Managed to figure this out. Final working code is:

<select id="dropdown" name="dropdown" value="hello">
<option value="0" data-imagesrc="images/icons/all.png">All Questions</option>
<option value="1" id="friends" data-imagesrc="images/icons/friends.png">Friends</option>
<option value="2" data-imagesrc="images/icons/friends_of_friends.png">Friends of Friends</option>
<option value="3" data-imagesrc="images/icons/network.png"><?php echo $network; ?></option>
<option value="4" data-imagesrc="images/icons/location.png"><?php echo $location ?></option>
</select>

<script type="text/javascript">
$('#dropdown').ddslick({
showSelectedHTML: false,
onSelected: function(data){
alert(data.selectedData.value);
}
});
</script>

Answer

According to the docs for your plugin, the onSelected method gets the selectedData parameter:

selectedData (nested object with text, value, description, imageSrc)

The text label and value are available as selectedData.text and selectedData.value inside the onSelected function. Try this:

$('#dropdown').ddslick({
    showSelectedHTML: false,
    onSelected: function(selectedData){
        var str = selectedData.value
        alert(str);
    }   
});
Comments