1
$('#arrow-left').click(function() {

    var sel = $('#right option:selected').val();

    $('#left').append('<option value="'+sel+'">'+ sel +'</option>');

});

The above is my code. I append an option from a selectbox #right into a selectbox #left upon click. However, I need to make sure that an option is selected in the #right or I get "undefined" options in the #left select form.

Anyone know how I can do this?

0

3 Answers 3

5

Check whether a selected option exists

$('#arrow-left').click(function () {
    var $selected = $('#right option:selected');
    if ($selected.length) {
        var sel = $selected.val();
        $('#left').append('<option value="' + sel + '">' + sel + '</option>');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Well, with $('#right').val() you'd be getting the current value of the select, no matter if user-selected or default.

$('#arrow-left').click(function() {
    var sel = $('#right').val();
    $('#left').append('<option value="'+sel+'">'+ sel +'</option>');
});

Comments

0

http://jsfiddle.net/aamir/KsQUX/

var $sel1 = $('select:first'),
    $sel2 = $('select:last');


$sel1.change(function(){
    var $op = $(this).find('option:selected');
    $sel2.append($op);
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.