Skip to main content

Bug Tracker

Side navigation

#4924 closed enhancement (invalid)

Opened July 19, 2009 05:41PM UTC

Closed November 18, 2010 03:12AM UTC

Use .val( true ) to return option.text instead of option.value

Reported by: ALLPRO Owned by:
Priority: minor Milestone: 1.4
Component: core Version: 1.3.2
Keywords: option val value text Cc:
Blocked by: Blocking:
Description

I often need to retrieve the 'display text' for the selected OPTION in a SELECT.

CURRENTLY, the text is only returned if the OPTION __has no value__...

return (elem.attributes.value || {}).specified ? elem.value : elem.text;

It would be useful if returning elem.text could be __forced__ by passing 'true' as the value param.

This assumes 'true' is __not__ a valid setter 'value'. This seems to be the case as far as I can tell.

I think it intuitive that 'true' would be a getter 'parameter' and not a setter 'value'. It's not unusual for booleans to be used this way.

My suggested change addes a 'retText' flag that is used to decide whether to return 'value' or 'text'. Here are the changed sections:

1.3.2 - line 409 - add & use retText flag

val: function( value ) {
    var retText = value === true;
    if ( value === undefined || retText ) {
        var elem = this[0];

        if ( elem ) {
            if( jQuery.nodeName( elem, 'option' ) )
                return (elem.attributes.value || {}).specified && !retText ? elem.value : elem.text;

1.3.2 - line 433 - pass retText back to val()

    if ( option.selected ) {
        // Get the specific value for the option
        value = jQuery(option).val( retText );

ALTERNATIVELY, passing 'true' could return a hash containing BOTH value and text, like...

return { value: elem.value, text: elem.text };

''This is just pseudo-code - would have to validate that option.value exists. Best to slightly restructure existing validation to avoid repeating it.''

Returning a hash avoids 2 calls to retrieve both value and text, just as offset returns both top & left. It is still simple to use when you *only* want the text...

var text  = $('#mySelect').val( true ).text

Either format would address the need to retrieve option.text. The first method is simpler because it returns a single value, but the second method is more versatile.

As long as 'true' is not a valid setter value, this enhancement provides new versatility without any problems or compatibility issues.

/Kevin Dalman

Attachments (0)
Change History (2)

Changed July 21, 2009 02:06AM UTC by dmethvin comment:1

If you want the text consistently, couldn't you just use

.text()
instead?

Changed November 18, 2010 03:12AM UTC by dmethvin comment:2

resolution: → invalid
status: newclosed

Use .text() instead.