117

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.

Mathieu
  • 4,449
  • 7
  • 41
  • 60
Karim Ali
  • 2,243
  • 6
  • 23
  • 31
  • 4
    What would be the difference between a readonly dropdown and a standard dropdown? – Leo Nov 11 '11 at 21:45
  • 1
    possible duplicate of [Setting a control to readonly using jquery 1.6 .prop()](http://stackoverflow.com/questions/5891734/setting-a-control-to-readonly-using-jquery-1-6-prop) – Blazemonger Nov 11 '11 at 21:45
  • Is this really a jQuery issue? Or maybe dropdown just doesn't work with readonly attribute? – Ilia G Nov 11 '11 at 21:45
  • Kanishka Panamaldeniya already gave you the correct answer (should make it an answer instead of a comment). – qbantek Nov 11 '11 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 '13 at 19:00
  • @Leo, the difference would be a read-only drop-down can not be change. E.g., if it has the options "A", "B", and "C", and it's currently showing "B", then the user can not change it to "A" or "C". As a matter of practicality, it's the same as "disabled", however, the "readonly" components and "disabled" components tend to have a different look. – UncaAlby Mar 06 '17 at 21:01

24 Answers24

215
$('#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

Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193
  • 32
    Making a dropdown disabled doesn't submit. I will try your solution. – Karim Ali Nov 12 '11 at 00: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 '13 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 '14 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 04 '14 at 13:35
  • Using disabled attribute instead of readonly can be dangerous because disabled elements are not sent to server once form is submitted. Be careful with it. – ikryvorotenko Sep 03 '15 at 08:23
  • 5
    You should be using `prop()` now. – alex Jan 26 '16 at 10:33
  • 1
    @kanishka Panamaldeniya if i am making chosen disable then i cannot get its value – Jay Momaya Jun 10 '17 at 10:43
171

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);
G_real
  • 1,137
  • 1
  • 18
  • 28
Bertrand D.
  • 1,711
  • 1
  • 10
  • 2
35

This is what you are looking for:

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

Works like a charm.

24

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

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

It works for me..

Prabhagaran
  • 3,620
  • 1
  • 19
  • 19
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 );
});     
NL3294
  • 984
  • 1
  • 10
  • 27
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>
Lucas Bustamante
  • 15,821
  • 7
  • 92
  • 86
13

Simple jquery to remove not selected options.

$('#your_dropdown_id option:not(:selected)').remove();
abhi chavda
  • 153
  • 1
  • 11
6

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

Arthur Corenzan
  • 901
  • 9
  • 17
  • 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. – Alex Hopkins May 05 '15 at 13:08
3

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

$('select[readonly=readonly] option:not(:selected)').prop('disabled', true);
dwitvliet
  • 7,242
  • 7
  • 36
  • 62
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.

Awais Tariq
  • 7,724
  • 5
  • 31
  • 54
3

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;} ?>>
DreK
  • 31
  • 2
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);
});
Homer
  • 7,594
  • 14
  • 69
  • 109
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.

Andrej
  • 49
  • 3
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

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>
Amiya
  • 41
  • 8
1

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

Hictus
  • 210
  • 2
  • 12
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 = "";
});
Hendro
  • 1
  • 2
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

Monicalh
  • 101
  • 1
  • 5
0

html5 supporting :

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

`

Atul Kumar
  • 324
  • 4
  • 8
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.

DaveInMaine
  • 899
  • 9
  • 12
0

Try This

$('#Dropdown').attr('readonly', true);
$('#Dropdown').css('pointer-events','none');
Merrin K
  • 1,602
  • 1
  • 16
  • 27
0

$("select[id='name_a1234dc4-1234-12a7-b..._DropDownChoice']").prop('disabled',true).att("style","pointer-events:none;");

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 25 '23 at 09:41
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/

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
  • 3
    not good if the currently selected option is not first in the list as in this example: http://jsfiddle.net/4aHcD/19/ – Homer Jan 25 '13 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 http://jsfiddle.net/4aHcD/20/ – Alex Turpin Jan 25 '13 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: http://jsfiddle.net/4aHcD/22/ – Homer Jan 25 '13 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 '13 at 19:02