tonyf
tonyf

Reputation: 35587

How to set the value of a select box when it is enabled only?

I have a top level select box that when a user makes a selection here, I want this value to be used for all the below select boxes relating to this top level box.

The problem I am having is that, if any one of the lower select boxes is disabled, I want the above process to ignore this select box as it has already been assigned a value.

Obviously, if the lower select box is enabled then I want to assign the top select value to it.

To disable the select list based on a particular value, I have used:

$("select[name=f03]").eq(index).attr('disabled', 'disabled');

Here is the jQuery that I have used but is not working:

var top_select = $("select[name=f07]").val();
$("select[name=f03]").each(function(index){
    if $("select[name=f03]").eq(index).is(':enabled'){
        $("select[name=f03]").eq(index).val(top_select);
    }
});

From this code, it is the lower selects ([name=f03]) that I am trying to set only when it is enabled.

Upvotes: 0

Views: 141

Answers (3)

KyawLay
KyawLay

Reputation: 403

you should use jquery :enabled selector as follow

  $("select[name=f03]:enabled").each(function(){   
   //execution
 });

or

 $("select[name=f03]:enabled").val("value");

here is jsfiddle example http://jsfiddle.net/kso2oqr5/1/

Upvotes: 1

Jadran Josimovic
Jadran Josimovic

Reputation: 86

First I would disable select like this: $("select[name=f03]").eq(index).prop('disabled', true);

Second, your function should be much simpler:

$("select[name=f03]").each(function(){
    if ($(this).prop('disabled')) return;
    $(this).val(top_select);
});

Upvotes: 1

Anton
Anton

Reputation: 32591

When you are disabling elements use .prop(property,value)

var top_select = $("select[name=f07]").val();
$('select[name="f03"]').val(function(){
    if(!this.disabled){
    return top_select;
    }
});

DEMO

Upvotes: 0

Related Questions