Skip to main content

Bug Tracker

Side navigation

#10140 closed bug (invalid)

Opened August 25, 2011 10:48PM UTC

Closed August 26, 2011 12:36AM UTC

Last modified August 28, 2011 02:49PM UTC

Set selected option fails

Reported by: tim_kiphuth@yahoo.com Owned by: tim_kiphuth@yahoo.com
Priority: low Milestone: None
Component: attributes Version: 1.6.2
Keywords: Cc:
Blocked by: Blocking:
Description

To add and select a select option, this works in 1.4.2 -

$("option[text='"+optName+"']", selEl).attr('selected', true);

In 1.4.3+, it doesn't work. Test case:

<html>

<title>Testcase - works</title>

<head>

<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>

<script language="javascript" type="text/javascript">

function updateSelect (optName) {

var selEl = $('select#color')[0];

if ($("option[text='"+optName+"']", selEl).length==0) {

$(selEl).append($('<option>').text(optName));

}

$("option[text='"+optName+"']", selEl).attr('selected', true);

return;

}

</script>

</head>

<body>

<select id="color"><option>Red<option>Green<option>Blue</select>

<input type="text" onChange="javascript:updateSelect(this.value)" />

</body>

</html>

This test takes the input and checks if the name is in the option list. If not, it adds the name to the options and selects the new name. Changing the version of jQuery to 1.4.3 or 1.6.2 will cause the select to fail. The option is added correctly, just not selected.

Attachments (0)
Change History (3)

Changed August 25, 2011 11:22PM UTC by rwaldron comment:1

component: unfiledattributes
owner: → tim_kiphuth@yahoo.com
priority: undecidedlow
status: newpending

Thanks for taking the time to contribute to the jQuery project! Please provide a complete reduced test case on jsFiddle to help us assess your ticket!

Additionally, be sure to test against the jQuery Edge version to ensure the issue still exists. To get you started, use this boilerplate: http://jsfiddle.net/FrKyN/

Open the link and click to "Fork" (in the top menu) to get started.

Changed August 26, 2011 12:36AM UTC by dmethvin comment:2

resolution: → invalid
status: pendingclosed

As you can see in your markup, there is no text *attribute*; there is not even a value attribute. So it is correct that nothing is matched.

In some cases, and in older versions of jQuery, selectors may end up matching a *property* instead of (or in addition to) attributes, but this is not behavior you should depend on.

If you want to match the text inside an option take a look at the :contains() selector.

Changed August 28, 2011 02:49PM UTC by tim_kiphuth@yahoo.com comment:3

Thanks, the :contains() selector will get'er done.