Search code examples
jquerydrop-down-menuhtml-select

Check last value of an drop-down option select box with jquery


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>

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.