Reputation: 741
I have 2 select boxes in the same fieldset. I am adding an option to both using jquery and I want them both to have the same default value.
$(function(){
var selectbox = $('.selectbox select');
selectbox.prepend('<option value="Select a question" selected="selected">Select a question</option>');
selectbox.children('option').each(function() {
var option = $(this);
option.removeAttr('disabled');
});
});
I even try to remove the disabled attribute that it sets and I can't seem to figure out why its setting the second selectbox as disabled for the option.
Upvotes: 0
Views: 201
Reputation: 87073
You have to prepend
the option to each select
using .each()
loop like below:
var selectbox = $('.selectbox select');
selectbox.each(function() {
$(this).prepend('<option value="Select a question" selected="selected">Select a question</option>');
});
Your code add option
to one select
. And you don't need to disable
them for prepend
purpose.
If your option
has disabled
attribute, I think this should not make any problem with above code. SEE HERE.
And to remove disabled
attribute from all option
you can do:
var selectbox = $('.selectbox select');
selectbox.each(function() {
$(this).find('option').removeAttr('disabled'); // remove disabled attr
$(this).prepend('<option value="Select a question" selected="selected">Select a question</option>');
});
Upvotes: 1
Reputation: 2482
This could be done by finding select menus, then prepend option element, then finding the first option and setting it selected:
$('.selectbox select')
.prepend('<option value="Select a question" selected="selected">Select a question</option>')
.find('option:first-child').attr('selected', 'selected');
Upvotes: 0