1

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>
3

3 Answers 3

2

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.

2

try using last

 $('#status option:last')

JSFIDDLE DEMO

3
  • @samyb8, check the fiddle link in my answer. It works fine. What browser and version do you use? Nov 1, 2013 at 15:40
  • yes I see. I posted the full code in case I am missing something. Can't find where...
    – samyb8
    Nov 1, 2013 at 15:41
  • @samyb8. check this fiddle. Also what is status and statusList? two elements? Nov 1, 2013 at 15:46
0
$(function() {
    var lastOpt = $('#status').find('option:last-child').attr('value');
    if (lastOpt === 'SHIPPED') { //blah }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.