user3218338
user3218338

Reputation: 682

jquery check if a option is selected

$('#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?

Upvotes: 1

Views: 390

Answers (3)

Aamir Afridi
Aamir Afridi

Reputation: 6411

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

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


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

Upvotes: 0

pontoffeltier
pontoffeltier

Reputation: 31

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>');
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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>');
    }
});

Upvotes: 5

Related Questions