3

I have some "select box" in my page and I don't want to let the user choose any option, but the first (please, don't ask me why). I can't change for 'input' with 'readonly' attribute and I can't remove the options either. I'm sorry for the limitations, but it has to be this way.

I tried this:

 $('select').attr('disabled',true);

But happens that I don't want to 'loose' the value. I have an ajax call that use those values and when I disable it, the value 'don't exist' anymore.

I tried this too:

 $('select').click(function(){
      return false;
 });

But without success.

1
  • 1
    No need for javascript at all, just disable the options rather than the select
    – Gareth
    Mar 21, 2011 at 19:18

5 Answers 5

6

You can do it with one line of code.

$('option').attr('disabled','disabled').eq(0).removeAttr('disabled');

Check working example at http://jsfiddle.net/yaGJc/1/

You can also make use of the :gt() greater then selector, although the first one gives more control on which option to have enabled.

$('option:gt(0)').attr('disabled','disabled');

Check working example at http://jsfiddle.net/yaGJc/2/

1

disable the options with jquery:

$('#selector option:gt(0)').attr('disabled', 'disabled');

Here is the fiddle

Should produce HTML like this:

<select multiple>
    <option>test1</option>
    <option disabled>test2</option>
    <option disabled>test3</option>
    <option disabled>test4</option>
    <option disabled>test5</option>
    <option disabled>test6</option>
</select>
0

Maybe you can try this

$('.select').attr('disabled', 'disabled');

I fought with this before...

0
var firstValue = $('select:first').val();
$('select:first').attr('disabled', true);

Then use the firstValue variable in the ajax call.

0

not sure y u would want to do something like tat but you can try

$("select option").each(function (index, obj) {
    if( index > 1 )
        $(obj).attr("disabled", "disabled");
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.