2

I want do do this in jQuery:

<option value="test" selected>...</option>

But everything I've tried gives me:

<option value="test" selected="selected">...</option>

I have tried .attr("selected", "") as well as .attr("selected", true), but they give the undesired selected="selected" result. How can I do this? Everything I've found on online suggests either the former or the latter of the above formats.

1
  • why are you even concerned about it? Commented Apr 6, 2015 at 22:51

1 Answer 1

6

You shouldn't worry about the attribute at all, you should be changing the property

$('option').prop('selected', true);

You can also set the selected option by just changing the value of the select (assuming it's not multiple)

$('select').val('test');

It doesn't matter what it looks like in the HTML, it's the representation in the DOM that matters, both for setting the option as selected and when submitting the form it's in.


FYI, <option value="test" selected="selected"> is not undesireable at all, it's completely valid and what you'd generally want.

When the selected attribute is present, the option is selected, regardless of the attributes value, even if it's empty the option will be selected.

Attributes should have values though, so selected="selected" is fine, and even something like selected="hello kitty" would select the option, to unselect it you'd remove the attribute, but again, you should be changing the property!!!

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, I tried this also, but for some reason it doesn't seem to make any difference. I don't get it. Why would .attr work but not .prop?
are you using latest jquery?
Well, first of all, both the HTML snippets you've posted in the question are valid, and generally you'd want the latter one, that's why you get that with attr. Secondly, as noted above, you should be changing the underlying property, not the attribute, but prop was added in jQuery 1.6, and hopefully you're using a newer version than that.
@adeneo, I understand that what you are suggesting is correct, but for some reason it isn't working for me. Surely there is an underlaying problem somewhere, so perhaps I have misidentified the issue. Regardless, I thank you. I'll keep investigating.
Start by opening the console (F12) and check for errors, and verify that you're using a current version of jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.