1

I have a set of listboxes

Here i want to readonly the particular options i.e

        <select name="list" id="l1">
        <option value="1" selected="selected" >1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="test">test</option>
        <option value="test2">test2</option>
        </select>

In the above list box i want to restrict the 'test' and 'test2 ' options as read only. User should not select these two options ('test', 'test2'). Is it possible in jquery

Please do the needful. Thanks

Sam Hanson
  • 1,317
  • 4
  • 22
  • 48

4 Answers4

2
<select name="list" id="l1">
    <option value="1" selected="selected">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5" >5</option>
    <option value="test" disabled>test</option>
    <option value="test2" disabled>test2</option>
</select>
user247702
  • 23,641
  • 15
  • 110
  • 157
mohan
  • 453
  • 1
  • 5
  • 17
2

Add a class to the disabled items (optionally graying them out with the class). Store the default value for the select list using the jQuery data attribute. On change, monitor whether a disabled option has been chosen. If so then revert to the stored value. Otherwise update stored value and continue.

http://jsfiddle.net/mrtsherman/Ew5uW/

//add class to disabled items
var len = $('option[value^="test"]').addClass('disabled');

//store default selected item value
$('#l1').data('selValue', $('#l1').val());

//monitor change events
$('#l1').change(function() {
    //if a disabled option is chosen then restore prev value
    if ($(this).children('option:selected').hasClass('disabled')) {
        $(this).val($(this).data('selValue'));
    }
    //otherwise store new value 
    $(this).data('selValue', $(this).val());
});​
mrtsherman
  • 39,342
  • 23
  • 87
  • 111
1

try this jquery :

   $(document).ready(function () {

  $("select[id='l1'] option").each(function()
  {
       var s = $(this).val();
       if(s == 'test' || s == 'test2')
         {

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

         }

  });

 });

hops its helps

Jignesh Rajput
  • 3,538
  • 30
  • 50
0

Try this ,

$("#l1").change(function()
{
if($(this).val()=="test" || $(this).val()=="test2")
 {
   alert("This option is disabled..");
   return false;
 }
})
Akhil Thayyil
  • 9,263
  • 6
  • 34
  • 48