Question

I am trying to get the last option from a drop down Select box with jquery.

I do this:

var maxOpt = $('#status option:last-child').val();
if (maxOpt != "SHIPPED") {
    console.log(maxOpt);
}

Console keeps printing undefined, even if the last option is SHIPPED.


FULL CODE

<script>
                    $(document).ready(function() {

                      $("#source").change(function() {

                        var el = $(this) ;
                        var sel = document.getElementById('statusList');
                        var maxOpt = $('#status option:last-child').val();
                        if((el.val() === "ONLINE" || el.val() === "ETSY") && maxOpt !="SHIPPED") {
                        $("#statusList").append("<option value='shipped'>SHIPPED</option>");
                        console.log(maxOpt);
                        }
                          else if(el.val() === "MANUAL" ) {
                            $("#statusList option:last-child").remove() ; }
                      });

                    });
                </script>
Was it helpful?

Solution

It works for me http://jsfiddle.net/zvkCp/ Maybe is a problem with your selector :

$('#status option:last-child')

$(document).ready (function() {
  var maxOpt = $('select option:last-child').val();
  if (maxOpt != 'cuatro'){
    console.log(maxOpt);
  }
})

Try to console.log(maxOpt) off the if condition.

OTHER TIPS

try using last

 $('#status option:last')

JSFIDDLE DEMO

$(function() {
    var lastOpt = $('#status').find('option:last-child').attr('value');
    if (lastOpt === 'SHIPPED') { //blah }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top