Reputation: 1967
I have a html select field and two javascript methods - one to enable a select field and another one to enable:
enable(){
$('#s').prop('disabled', false);
}
disable(){
$('#s').prop('disabled', true);
}
<select id="s">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Now calling enable and disable methods do what they are intended for. But in addition to just disabling the field in disable method i would also like the field to say "unavailable" when disabled. I couldnt find a way to show something like this in a select field without actually having a option. So is the best solution to add an option to the select in disable method and set it as selected and then remove it in enable method or is there something cleaner available?
Upvotes: 0
Views: 1107
Reputation: 6766
You can merge both functions into one.
function toggleDisabled() {
var dropdown = $('#s');
var disabled = dropdown.prop('disabled');
if (!disabled) {
// add option to the top of the list
dropdown.prepend('<option>unavailable</option>');
} else {
// remove any option with no value
$('option:not([value])', dropdown).remove();
}
// flip disabled and change current value to first
dropdown.prop('disabled', !disabled).val($('option:first', dropdown).val());
}
// just for testing
$('button').click(function() {
toggleDisabled();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button>click me</button>
Upvotes: 3
Reputation: 2482
Since you don't want an option in the select box. Just use display:none;
to show and hide a text box with the value Unavailable.
function enable(){
$('#s').css('visibility', "visible");
$('#s_text').css("display", "none");
}
function disable(){
$('#s').css('visibility', "hidden");
$('#s_text').css("display", "inline");
}
<body>
<select id="s">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input id="s_text" style="display:none;" type="text" disabled value="Unavailble" />
<button onclick="enable();"> Enable</button>
<button onclick="disable();"> Disable </button>
</body>
Upvotes: 1