View Single Post
Old 08-18-2010, 06:43 PM   PM User | #1
VIPStephan
The fat guy next door


 
VIPStephan's Avatar
 
Join Date: Jan 2006
Location: Halle (Saale), Germany
Posts: 7,607
Thanks: 5
Thanked 865 Times in 842 Posts
VIPStephan is a jewel in the roughVIPStephan is a jewel in the roughVIPStephan is a jewel in the rough
check if “selected” attribute is set explicitly

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');
});
__________________
Don’t click this link!
VIPStephan is offline   Reply With Quote