echo_Me
echo_Me

Reputation: 37243

making one option disabled after selecting

I have tried to bind those two code ideas together but it isn't working.

I want to disable the first option from being selectable after a selection has been made.

This is the behavior I'm wanting; the first option is disabled after a selection is made.

And this is my code where I want the first option disabled when a subsequent element is picked.

Upvotes: 0

Views: 685

Answers (2)

veeTrain
veeTrain

Reputation: 2915

I believe this answers your inquiry:

http://jsfiddle.net/dq97z/66/

Inside of displayVals I executed the following:

if ($("#menucompare").prop("selectedIndex") !== "0") {
    // Within the select (you could be more specific) find
    // the first (direct descendant) option value and 
    // disable it to make it unselectable
    $("select > option:first").prop("disabled", "disabled")
}

This segment finds out what the selected index of your select menu is and if the user has selected something other than the initial one (0), it sets the first option to be disabled.

Update: http://jsfiddle.net/dq97z/72/

Changed attr() to prop() when disabling per the documentation and @silkster's advice. Thanks

Also, if you don't want the option selectable at the beginning, you could even do it without an if statement as seen here.

function displayVals() {
    var singleValues = $("select option:selected").text();
    ....
    $("select > option:first").prop("disabled", "disabled")
}

The disabling happens after the DOM is loaded (with the first one not disabled) so the select can still have 'Please select' selected. Whoah...that's a lot of "select"s.

If you want to leave the if statement there (which means 'select one' is selectable until another is actually selected), your if statement would need to be like this:

if ($("#menucompare").prop("selectedIndex") !== 0) // with no quotes around zero

Upvotes: 1

Silkster
Silkster

Reputation: 2210

[UPDATED ANSWER]

http://jsfiddle.net/N9JEx/2/

function displayVals() {
    var singleValues = $("select option:selected").text();
    if (!isNaN(singleValues )) {
        $("#hiddenselect").val(singleValues);
        $("<p></p>").html("Percent of : &nbsp" + singleValues).appendTo('body');
    }
}

$(document).ready(function() {
    $("select").change(function() {
        displayVals();
        if (this.selectedIndex > 0) {
            var option = $('option:selected', this);
            option.prop('disabled', true);
        }
    });
});​

Upvotes: 1

Related Questions