According to HTML specs, the select
tag in HTML doesn\'t have a readonly
attribute, only a disabled
attribute. So if you want to keep
Below worked for me :
$('select[name=country]').attr("disabled", "disabled");
If you are using jquery validate, you can do the following below, I used the disabled attribute without a problem:
$(function(){
$('#myform').validate({
submitHandler:function(form){
$('select').removeAttr('disabled');
form.submit();
}
});
});
I know that it is far too late, but it can be done with simple CSS:
select[readonly] option, select[readonly] optgroup {
display: none;
}
The style hides all the options and the groups when the select is in readonly
state, so the user can not change his selection.
No JavaScript hacks are needed.
Yet another more contemporary option (no pun intended) is to disable all the options of the select element other then the selected one.
note however that this is an HTML 4.0 feature and ie 6,7,8 beta 1 seem to not respect this.
http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/OptionDisabledSupport.html
Simple CSS solution:
select[readonly]{
background: #eee;
cursor:no-drop;
}
select[readonly] option{
display:none;
}
This results in Select to be gray with nice "disable" cursor on hover
and on select the list of options is "empty" so you can not change its value.
You should keep the select
element disabled
but also add another hidden input
with the same name and value.
If you reenable your SELECT, you should copy its value to the hidden input in an onchange event and disable (or remove) the hidden input.
Here is a demo:
$('#mainform').submit(function() {
$('#formdata_container').show();
$('#formdata').html($(this).serialize());
return false;
});
$('#enableselect').click(function() {
$('#mainform input[name=animal]')
.attr("disabled", true);
$('#animal-select')
.attr('disabled', false)
.attr('name', 'animal');
$('#enableselect').hide();
return false;
});
#formdata_container {
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form id="mainform">
<select id="animal-select" disabled="true">
<option value="cat" selected>Cat</option>
<option value="dog">Dog</option>
<option value="hamster">Hamster</option>
</select>
<input type="hidden" name="animal" value="cat"/>
<button id="enableselect">Enable</button>
<select name="color">
<option value="blue" selected>Blue</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<input type="submit"/>
</form>
</div>
<div id="formdata_container" style="display:none">
<div>Submitted data:</div>
<div id="formdata">
</div>
</div>