Bug Tracker

Opened 10 years ago

Closed 9 years ago

#4924 closed enhancement (invalid)

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

Change History (2)

comment:1 Changed 10 years ago by dmethvin

If you want the text consistently, couldn't you just use .text() instead?

comment:2 Changed 9 years ago by dmethvin

Resolution: invalid
Status: newclosed

Use .text() instead.

Note: See TracTickets for help on using tickets.