114

I am using the following statement to make it readonly but it is not working.

$('#cf_1268591').attr("readonly", "readonly"); 

I don't want make it disabled, I want to make it readonly.

6
  • 4
    What would be the difference between a readonly dropdown and a standard dropdown?
    – Leo
    Nov 11, 2011 at 21:45
  • 1
    possible duplicate of Setting a control to readonly using jquery 1.6 .prop() Nov 11, 2011 at 21:45
  • Is this really a jQuery issue? Or maybe dropdown just doesn't work with readonly attribute?
    – Ilia G
    Nov 11, 2011 at 21:45
  • Kanishka Panamaldeniya already gave you the correct answer (should make it an answer instead of a comment).
    – qbantek
    Nov 11, 2011 at 21:48
  • 2
    Dropdown is not always read-only. Read-only means you can see its value but can't change it.
    – Suncat2000
    Dec 12, 2013 at 19:00

23 Answers 23

213
$('#cf_1268591').attr("disabled", true); 

drop down is always read only . what you can do is make it disabled

if you work with a form , the disabled fields does not submit , so use a hidden field to store disabled dropdown value

7
  • 32
    Making a dropdown disabled doesn't submit. I will try your solution.
    – Karim Ali
    Nov 12, 2011 at 0:40
  • 3
    One problem with making a select (drop-down) disabled is that focus is lost in some browsers (e.g. IE9). This can be a problem if the select element is being disabled while an ajax call is processed, for example, as the user's position in the form is lost.
    – Chris
    Feb 19, 2013 at 10:47
  • 1
    Thanks for your suggestion. Just a question though; how would I store the drop down value in a hidden field? Would you have some example code for that?
    – kramer65
    Apr 20, 2014 at 12:14
  • 3
    Another "workaround" would be to enable those fields prior to form submission. Or in my case where I sent the data in JSON format (enable, get data, disable again): var disabled = $(yourform).find(':input:disabled').removeAttr('disabled'); var data = getFormJSONData($(yourform)); disabled.attr('disabled', 'disabled');
    – KDT
    Jul 4, 2014 at 13:35
  • 5
    You should be using prop() now.
    – alex
    Jan 26, 2016 at 10:33
170

I had the same problem, my solution was to disable all options not selected. Very easy with jQuery:

$('option:not(:selected)').attr('disabled', true);

Edit => If you have multiple dropdowns on same page, disable all not selected options on select-ID as below.

$('#select_field_id option:not(:selected)').attr('disabled', true);
5
  • 31
    Great idea! To use best practices with current versions of jQuery, I'd use the prop method to set the disabled value. ie $('option:not(:selected)').prop('disabled', true); Oct 16, 2013 at 20:02
  • This is a very witty solution!
    – Jacques
    Sep 17, 2018 at 11:13
  • 1
    YES! great idea.
    – Eric
    Sep 26, 2018 at 13:57
  • 1
    This should be n°1 answer. Feb 20, 2019 at 15:41
  • Or remove it $('option:not(:selected)').remove(); Apr 19, 2022 at 9:12
33

This is what you are looking for:

$('#cf_1268591').attr("style", "pointer-events: none;");

Works like a charm.

3
  • 2
    Great answer but beware this still allows the select to tabbed to. You also need to set the tabindex="-1" Dec 28, 2017 at 14:32
  • Great Man, I need this, as disabled not mapped to the model thanks for your answer.
    – sina_Islam
    Apr 11, 2018 at 9:46
  • Thank you so much! I appreciate your help :)
    – fahdshaykh
    Jun 23, 2021 at 16:53
24

Try this one.. without disabling the selected value..

$('#cf_1268591 option:not(:selected)').prop('disabled', true);

It works for me..

1
  • 1
    Along the same line as your answer I removed the other options $('#cf_1268591 option:not(:selected)').remove(); Sep 14, 2016 at 12:31
16

I'd make the field disabled. Then, when the form submits, make it not disabled. In my opinion, this is easier than having to deal with hidden fields.

//disable the field
$("#myFieldID").prop( "disabled", true );           

//right before the form submits, we re-enable the fields, to make them submit.
$( "#myFormID" ).submit(function( event ) {
    $("#myFieldID").prop( "disabled", false );
});     
14

Setting an element with disabled will not submit the data, however select elements don't have readonly.

You can simulate a readonly on select using CSS for styling and JS to prevent change with tab:

select[readonly] {
  background: #eee;
  pointer-events: none;
  touch-action: none;
}

Then use it like:

var readonly_select = $('select');
$(readonly_select).attr('readonly', true).attr('data-original-value', $(readonly_select).val()).on('change', function(i) {
    $(i.target).val($(this).attr('data-original-value'));
});

Result:

  // Updated 08/2018 to prevent changing value with tab
$('a').on('click', function() {
var readonly_select = $('select');
$(readonly_select).attr('readonly', true).attr('data-original-value', $(readonly_select).val()).on('change', function(i) {
	$(i.target).val($(this).attr('data-original-value'));
});
});
select[readonly] {
  background: #eee;
  pointer-events: none;
  touch-action: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Click here to enable readonly</a>
<select>
<option>Example 1</option>
<option selected>Example 2</option>
<option>Example 3</option>
</select>

2
  • 3
    Very cool approach, but the user can still use TAB on keyboard to select a value. Feb 13, 2018 at 0:30
  • 1
    @RicardoMartins thanks, updated the answer to prevent change with TAB Aug 8, 2018 at 14:18
12

Simple jquery to remove not selected options.

$('#your_dropdown_id option:not(:selected)').remove();
1
  • Also my solution. Better than make them disabled. May 24, 2019 at 14:48
6

To simplify things here's a jQuery plugin that does that without the hassle: https://github.com/haggen/readonly

1
  • Great (tiny) snippet of code, thanks. It disables dropdowns so they cant be changed but still allows for their values to be submitted. Very useful. May 5, 2015 at 13:08
3

This line makes selects with the readonly attribute read-only:

$('select[readonly=readonly] option:not(:selected)').prop('disabled', true);
3

It´s work very well

$('#cf_1268591 option:not(:selected)').prop('disabled', true);

With this I can see the options but I can't select it

3

Easiest option for me was to make select as readonly and add:

onmousedown="return false" onkeydown="return false"

You don't need to write any extra logic. No hidden inputs or disabled and then re-enabled on form submit.

2

This code will first store the original selection on each dropdown. Then if the user changes the selection it will reset the dropdown to its original selection.

http://jsfiddle.net/4aHcD/22/

//store the original selection
$("select :selected").each(function(){
    $(this).parent().data("default", this);
});

//change the selction back to the original
$("select").change(function(e) {
    $($(this).data("default")).prop("selected", true);
});
2

I know this is an old topic, but I thought I would respond for anyone else wanting to make a select field read-only, not disabled.

Select field can't have a read-only attribute. The best way I found was using a CSS.

This will make the select field act as if its read-only, while still submitting the value.

To make a field act as read-only:

$("#FieldId").css({"pointer-events": "none", "touch-action": "none", "background": "#ede6e6"});

To make a field actionable:

$("#FieldId").css({"pointer-events": "auto", "touch-action": "auto", "background": "#ffffff"});

I also use this if I have a form with multiple fields that need to be made read-only based on access level, by declaring it in a variable. E.G PHP

if($UserAccess == "Limited"){
$ReadOnlyFields = "style='pointer-events:none;touch-action:none;background:#ede6e6;'";
}

<select name='TheField' <?php if(!empty($ReadOnlyFields)){echo $ReadOnlyFields;} ?>>
1

It is an old article, but i want to warn people who will find it. Be careful with disabled attribute with got element by name. Strange but it seems not too work.

this do not work:

<script language="JavaScript">
function onChangeFullpageCheckbox() {    
$('name=img_size').attr("disabled",$("#fullpage").attr("checked"));
</script>

this work:

<script language="JavaScript">
function onChangeFullpageCheckbox() {    
$('#img_size').attr("disabled",$("#fullpage").attr("checked"));
</script>

Yes, i know that i better should use prop and not attr, but at least now prop will not work because of old version of jquery, and now i cant update it, dont ask why... html difference is only added id: ...

<select name="img_size" class="dropDown" id="img_size">
<option value="200">200px
</option><option value="300">300px
</option><option value="400">400px
</option><option value="500">500px
</option><option value="600" selected="">600px
</option><option value="800">800px
</option><option value="900">900px
</option><option value="1024">1024px
</option></select>

<input type="checkbox" name="fullpage" id="fullpage" onChange="onChangeFullpageCheckbox()" />

...

I have not found any mistakes in the script, and in the version with name, there was no errors in console. But ofcourse it can be my mistake in code

Seen on: Chrome 26 on Win 7 Pro

Sorry for bad grammar.

1

I've found, a better way to do this is to use CSS to remove pointer-events and modify the opacity on the drop down (try 0.5). This gives the appearance to the user that it is disabled as normal, but still posts data.

Granted this has some issues with backwards compatibility, but is in my opinion a better option than getting around the annoying disabled/readonly issue.

1
  • Can you elaborate on the CSS required to do this?
    – Cocowalla
    Jan 22, 2015 at 11:15
1

You could also disable it and at the moment that you make the submit call enable it. I think is the easiest way :)

1

As @Kanishka said , if we disable a form element it will not be submitted . I have created a snippet for this problem . When the select element is disabled it creates a hidden input field and store the value . When it is enabled it delete the created hidden input fields .

More info

jQuery(document).ready(function($) {
  var $dropDown = $('#my-select'),
    name = $dropDown.prop('name'),
    $form = $dropDown.parent('form');

  $dropDown.data('original-name', name); //store the name in the data attribute 

  $('#toggle').on('click', function(event) {
    if ($dropDown.is('.disabled')) {
      //enable it 
      $form.find('input[type="hidden"][name=' + name + ']').remove(); // remove the hidden fields if any
      $dropDown.removeClass('disabled') //remove disable class 
        .prop({
          name: name,
          disabled: false
        }); //restore the name and enable 
    } else {
      //disable it 
      var $hiddenInput = $('<input/>', {
        type: 'hidden',
        name: name,
        value: $dropDown.val()
      });
      $form.append($hiddenInput); //append the hidden field with same name and value from the dropdown field 
      $dropDown.addClass('disabled') //disable class
        .prop({
          'name': name + "_1",
          disabled: true
        }); //change name and disbale 
    }
  });
});
/*Optional*/

select.disabled {
  color: graytext;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="#" name="my-form">
  <select id="my-select" name="alpha">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
  </select>
</form>
<br/>
<button id="toggle">toggle enable/disable</button>

0

There is no such thing as a read-only drop-down. What you could do is reset it to the first value manually after each change.

$("select").change(function(event) {
    $(this).val($(this).find("option").first().val());
});

http://jsfiddle.net/4aHcD/

4
  • 3
    not good if the currently selected option is not first in the list as in this example: jsfiddle.net/4aHcD/19
    – Homer
    Jan 25, 2013 at 17:32
  • @Homer, the code is intended to reset it after any change, and it works in that effect. If you want it to run initially instead of changing the initial value yourself for some reason, you can always call the change event on your element after declaring the event, using $("select").change(), like so jsfiddle.net/4aHcD/20 Jan 25, 2013 at 20:33
  • 2
    when the page is first loaded, if the third item is selected and the user tries to change it to the second item, your code changes the selection to the first item. I don't think it should not do that. Here is an example of what I think the OP wanted, a dropdown that will not change its selected value based on user interaction: jsfiddle.net/4aHcD/22
    – Homer
    Jan 25, 2013 at 21:07
  • What I need and what the OP was requesting was a way to make it read-only. That means you can see the selected value or values but cannot change it. That means the display mimics the appearance of the editable control without being able to edit it.
    – Suncat2000
    Dec 12, 2013 at 19:02
0

Try to make empty string when "keypress up"

The Html is:

<input id="cf_1268591" style="width:60px;line-height:16px;border:1px solid #ccc">

The Jquery is:

$("#cf_1268591").combobox({
  url:"your url",
  valueField:"id",
  textField:"text",
  panelWidth: "350",
  panelHeight: "200",
});

// make after keyup with empty string

var tb = $("#cf_1268591").combobox("textbox");
  tb.bind("keyup",function(e){
  this.value = "";
});
0

Maybe you can try this way

function myFunction()
{
   $("select[id^=myID]").attr("disabled", true);
   var txtSelect = $("select[id^=myID] option[selected]").text();
}

This sets the first value of the drop-down as the default and it seems readonly

0

html5 supporting :

`
     $("#cCity").attr("disabled", "disabled"); 
     $("#cCity").addClass('not-allow');

`

0

Here is a slight variation on the other answers that suggest using disabled. Since the "disabled" attribute can actually have any value and still disable, you can set it to readonly, like disabled="readonly". This will disable the control as usual, and will also allow you to easily style it differently than regular disabled controls, with CSS like:

select[disabled=readonly] {
    .... styles you like for read-only
}

If you want data to be included submit, use hidden fields or enable before submit, as detailed in the other answers.

0

Try This

$('#Dropdown').attr('readonly', true);
$('#Dropdown').css('pointer-events','none');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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