Here’s the situation: I am dynamically adding the label text that is assigned to a
select element as first option inside that select while hiding the label. Now when something is selected and the form is submitted it doesn’t show the manually selected option (which has a selected attribute set explicitly then) but always shows the first dynamically added one as the JS is setting the selected attribute on it on DOM ready. I need to find a way to only add that attribute if nothing else has a
selected attribute.
The problem is that
one option is always selected implicitly (the one that is shown in the dropdown list on the page) so I can’t use the
:selected selector as it will always return true, as well as the
option[selected] selector. It seems like there is no way to find out if any option has a hard coded
selected attribute, or is there?
My code looks like this:
Code:
<label for="select_id">Label text</label>
<select id="select_id">
<option value="">Option 1</option>
<option value="">Option 2</option>
<option value="">Option 3</option>
</select>
and
Code:
$('select').each(function() {
var id = $(this).attr('id');
var label = $(this).siblings('label[for='+id+']').hide();
var labelText = label.text();
$(this).prepend('<option>'+labelText+'</option>');
$(this).children('option').first().attr('selected','selected');
});