Reputation: 682
$('#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
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
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
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