How to Disable an <Option> in a <Select> Based on Its Value in JavaScript

How can I disable an option in a select based on its value in JavaScript?

JavaScript, in 2022

You can use querySelectorAll, and forEach off of the resulting NodeList to do this same thing more easily in 2022.

document.querySelectorAll("#foo option").forEach(opt => {
if (opt.value == "StackOverflow") {
opt.disabled = true;
}
});

Do be mindful of string-comparisons, however. 'StackOverflow' and 'stackoverflow' are not the same string. As such, you can call .toLowerCase() on strings before comparing, or even go with a case-insensitive regular expression comparison like the this:

if ( /^stackoverflow$/i.test(option.value) ) {
option.disabled = true;
}

Pure Javascript (2010)

With pure Javascript, you'd have to cycle through each option, and check the value of it individually.

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}

Without enabling non-targeted elements:

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}

###jQuery

With jQuery you can do this with a single line:

$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");

Without enabling non-targeted elements:

$("option[value='stackoverflow']").attr("disabled", "disabled");


Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:

$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});

Without enabling non-targeted elements:

$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled");
}
});

How to disable select option after a certain time?

Instead of calling the function at onChange event, call at document load or when document is ready.

For this particular need, is better approach if you have your intervals in options values, I used an interval like this value="10-11" it represents 10am to 11am.

If you use getHours() method, it returns the hours in military time based means that for 10pm it will return 22.

let element = document.getElementById('time1');
let validateInterval = (element) => {
let currentDate = new Date();
let currentHour = currentDate.getHours();

for (let opt of element.options) {
let timeOpt = opt.value.split('-');
if (Array.isArray(timeOpt) && timeOpt.length > 1) {
opt.disabled = (+timeOpt[0] <= currentHour && +timeOpt[1] > currentHour) ? false : true;
}
}
}

validateInterval(element);
<select id="time1">
<option value="" disabled selected>Select delivery time</option>
<option value="10-12">10:00 AM - 12:00 PM</option>
<option value="13-15">1:00 PM - 3:00 PM</option>
<option value="15-19">3:00 PM - 7:00 PM</option>
<option value="20-22">8:00 PM - 10:00 PM</option>
<option value="21-23">9:00 PM - 11:00 PM</option>
<option value="22-23">10:00 PM - 11:00 PM</option>
</select>

How to disable select option based on another select option

Try this:

$('#color').change(function(e){
if($(this).val() == "Pink"){
$("#size option[value='Medium']").prop('disabled',true);
}
else {
$("#size option[value='Medium']").prop('disabled',false);
}
});

Use 'prop' instead of 'attr'.

Demo:

http://jsfiddle.net/59knw46r/

Disable select options based on another select option after page load

In your other question, where it uses an anonymous function .onchange = function() — you will want to take that and make it a named function so it becomes (for example if you called that function "updateSelect") .onchange = updateSelect

Then you will want to run that function when the page loads, not just onchange, with something like document.addEventListener('DOMContentLoaded', updateSelect);

This assumes that, as you say, when the page reloads after your submit the value of the level select box is preserved and selected.

Adapting Louys Patrice Bessette's answer, I've pulled the function out to the top, set it up to be called when the page (DOM) is ready, and set it to be called onchange of the Level selection.

function updateSelect() {
const level = levelSelect.value;

// Ensure everything is enabled when no level selected (on first page load)
if (level === 'Select') {
gradeSelect.querySelectorAll('option[value]')
.forEach(o => o.disabled = false);
}

gradeSelect.querySelectorAll('option[value]')
.forEach(function(option) {
option.disabled = !(level === option.dataset.level)
});
// Sets the first one (Choose Grade Level) selected
gradeSelect.querySelector('option').selected = true;
}

let levelSelect = document.getElementById('level');
let gradeSelect = document.querySelector('.grade_level');

// Update the selection when the page loads, so if 'level' already has
// a value the grade_levels will be enabled/disabled appropriately.
document.addEventListener('DOMContentLoaded', updateSelect);

levelSelect.onchange = updateSelect;
<select name="level" id="level" autofocus>
<option selected disabled>Choose</option>
<option value="Junior">Junior</option>
<option value="Senior">Senior</option>
</select>

<select name="grade_level" class="grade_level">
<option selected disabled>Choose Grade Level</option>
<option value="Grade 7" data-level="Junior">Grade 7</option>
<option value="Grade 8" data-level="Junior">Grade 8</option>
<option value="Grade 9" data-level="Junior">Grade 9</option>
<option value="Grade 10" data-level="Junior">Grade 10</option>
<option value="Grade 11" data-level="Senior">Grade 11</option>
<option value="Grade 12" data-level="Senior">Grade 12</option>
</select>

disable select option based on a variable value

document.getElementById('put_date') == today.getDate() is not a valid statement, you should compare the value of the element (document.getElementById('put_date').value). I also invoke the function on change, because on init the value of the second select is empty (not really empty, it's equal to "Select date"):

function onChange() {  var today = new Date();  if (document.getElementById('put_date').value == today.getDate()) {    document.getElementById("t1").disabled = true;  } else {     document.getElementById("t1").disabled = false;  }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select name="time"  id = "put_time">  <option value="Select Time">Select Time</option>  <option value="6.00.00" id = "t1">6.00.00</option>  <option value="6.30.00" id = "t2">6.30.00</option>  <option value="7.00.00" id = "t3">7.00.00</option>  <option value="7.30.00" id = "t4">7.30.00</option> </select><select name="date" id = "put_date" onchange="onChange()">  <option value="Select date">Select Date</option>  <option value="11">11</option>  <option value="12">12</option>  <option value="13">13</option>  <option value="14">14</option>  <option value="15">15</option>  <option value="16">16</option>  <option value="17">17</option>  <option value="18">18</option>  <option value="19">19</option>  <option value="20">20</option></select>

enable / disable options based on another select option

Using a data-* attribute and the dataset property... Your code could be a lot more concise.

let gradeSelect = document.querySelector('.grade_level')
document.getElementById('level').onchange = function() {
let level = this.value;

gradeSelect.querySelectorAll('option[value]').forEach(function(option) {
option.disabled = !(level === option.dataset.level)
});
// Sets the first one (Choose Grade Level) selected
gradeSelect.querySelector('option').selected = true
};
<select name="level" id="level" autofocus>
<option selected disabled>Choose</option>
<option value="Junior">Junior</option>
<option value="Senior">Senior</option>
</select>

<select name="grade_level" class="grade_level">
<option selected disabled>Choose Grade Level</option>
<option value="Grade 7" data-level="Junior">Grade 7</option>
<option value="Grade 8" data-level="Junior">Grade 8</option>
<option value="Grade 9" data-level="Junior">Grade 9</option>
<option value="Grade 10" data-level="Junior">Grade 10</option>
<option value="Grade 11" data-level="Senior">Grade 11</option>
<option value="Grade 12" data-level="Senior">Grade 12</option>
</select>

How do I disable a select option based on another select option?

In your if statement that disables the lower two select elements you just need to change .val().length == 0 to .val and that will disable them when the top two are selected.

var start = 2010;var end = 2030;var options = "";for (var year = start; year <= end; year++) {  options += "<option>" + year + "</option>";}document.getElementById("idTahunBerlaku").insertAdjacentHTML(  "beforeend", options);
var start = 1;var end = 12;var options = "";for (var month = start; month <= end; month++) { options += "<option>" + month + "</option>";}document.getElementById("idBulanBerlaku").insertAdjacentHTML( "beforeend", options);
var start = 2010;var end = 2030;var options = "";for (var year = start; year <= end; year++) { options += "<option>" + year + "</option>";}document.getElementById("idTahunBerlakuS").insertAdjacentHTML( "beforeend", options);
var start = 1;var end = 12;var options = "";for (var month = start; month <= end; month++) { options += "<option>" + month + "</option>";}document.getElementById("idBulanBerlakuS").insertAdjacentHTML( "beforeend", options);
$('#idBtnSimpanSimpan').click( function() { if ($('#idPenerbit').val().length == 0 || $('#idtrainingName').val().length == 0) { alert("ISI SEMUA FORM TERLEBIH DAHULU"); } else { debugger; var vDatasertifikasi = $('#idFrmAddSertifikasi') .serialize(); alert(vDatasertifikasi); debugger; $.ajax({ url: '/savesertifikasi', type: 'POST', data: vDatasertifikasi, dataType: "json",
success: function(model) { debugger; if (model.status == "berhasil") { alert("Data berhasil disimpan"); $('#idMdlNewSertifikasi').modal('hide');
/* redirecting to home of barang */ debugger;
} else { alert("Data salah"); } }, error: function(model) { debugger; } }); } });
$(".clSelectKiri").change(function() { if ($('#idTahunBerlaku').val() && $('#idBulanBerlaku').val()) { $(".clTgglKanan").attr("disabled", false); } else { $(".clTgglKanan").attr("disabled", true); }}).trigger("change");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><form class="form-horizontal" id="idFrmAddSertifikasi" method="post">  <div class="row">    <div class="col-sm-12">      <div class="row">        <!-- LEVEL 1 / KIRI -->        <div class="col-xs-8 col-sm-6">          <div class="col-xs-12">            <label for="SertifikasiName" class="control-label">Nama              Sertifikasi<sup>*</sup>            </label>            <div class="form-group">              <div class="col-sm-12">                <input type="text" class="form-control clborderbiru" maxlength="50" id="idtrainingName" name="certificate_name" placeholder="" title="MAKS. KARAKTER 50">              </div>            </div>          </div>          <div class="col-xs-12 col-sm-12">            <label for="schoolName" class="control-label">Berlaku              Mulai</label>            <div class="row">              <div class="col-xs-8 col-sm-6">                <div class="form-group">                  <div class="col-sm-12">                    <select class="form-control clborderbiru clSelectKiri" id="idBulanBerlaku" name="valid_start_month">                      <option value="" disabled selected hidden>- Pilih                        Bulan -</option>                    </select>                  </div>                </div>              </div>              <div class="col-xs-4 col-sm-6">                <div class="form-group">
<div class="col-sm-12"> <select class="form-control clborderbiru clSelectKiri" id="idTahunBerlaku" name="valid_start_year"> <option value="" disabled selected hidden>- Pilih Tahun -</option> </select> </div> </div> </div> </div> </div>
</div>
<!-- LEVEL 2 / KANAN --> <div class="col-xs-4 col-sm-6">
<div class="col-xs-12"> <label for="organizer" class="control-label">Penerbit<sup>*</sup></label> <div class="form-group"> <div class="col-sm-12"> <input type="text" class="form-control clborderbiru" id="idPenerbit" name="publisher" placeholder=""> </div> </div> </div>
<div class="col-xs-12 col-sm-12"> <label for="schoolName" class="control-label">Berlaku Sampai</label> <div class="row"> <div class="col-xs-8 col-sm-6"> <div class="form-group"> <div class="col-sm-12"> <select class="form-control clTgglKanan clborderbiru" id="idBulanBerlakuS" name="until_month"> <option value="" disabled selected hidden>- Pilih Bulan -</option> </select> </div> </div> </div> <div class="col-xs-4 col-sm-6"> <div class="form-group">
<div class="col-sm-12"> <select class="form-control clTgglKanan clborderbiru" id="idTahunBerlakuS" name="until_year"> <option value="" disabled selected hidden>- Pilih Tahun -</option> </select> </div> </div> </div> </div> </div>
</div> </div> <div class="col-xs-12"> <label for="notes" class="control-label">Catatan</label> <div class="form-group"> <div class="col-sm-12"> <textarea class="form-control clborderbiru" id="idCatatan" rows="6" name="notes"></textarea> </div> </div> </div> <div class="col-md-offset-10"> <div class="btn-group"> <button type="button" class="btn clBtnMdl">Batal</button> <button type="button" class="btn clBtnMdl" id="idBtnSimpanSimpan">Simpan</button> </div> </div> </div> </div></form>

Disabling select2 options based on selected value

You can use evt.params.args.data.element this will give you option tag html then using this you can get the groupid value and compare it with all options attr if not same disabled that option.

Now , instead of unselecting use unselect because here you need to enable all options when select-box doesn't have any value selected . So , inside your function get select2('data').length and if length is 0 then only enabled all options.

Demo Code :

$(function() {
$('select').select2({
allowClear: true,
placeholder: "Pick a State"

});

$('select').on("select2:selecting", function(evt, f, g) {
disableSel2Group(evt, this, true);
});

$('select').on("select2:unselect", function(evt) {
disableSel2Group(undefined, undefined, false);
});

})

function disableSel2Group(evt, target, disabled) {
//check if disabled true
if (disabled) {
//get option
var selId = evt.params.args.data.element;
var group = $(selId).attr('groupid') //groupid

var aaList = $("option", target);
$.each(aaList, function(idx, item) {
var other_groups = $(item).attr("groupid"); //get option groupid
var data = $(item).data("select2-id"); //get option selct2id
//if not same
if (group != other_groups) {
$("select option[data-select2-id =" + data + "]").prop("disabled", true); //disable that option

}
})
} else {
var count = $('select').select2('data').length //checcking slected data count
console.log(count)
//if 0
if (count == 0) {
$("select option").prop("disabled", false); //enable all options
}
}
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css">

<script src="https://code.jquery.com/jquery-3.5.0.js"></script>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>

<select multiple style="width: 300px">

<option groupid="a" value="A_AK">Alaska</option>

<option groupid="b" value="B_HI">Hawaii</option>

<option groupid="c" value="C_CA">California</option>

<option groupid="a" value="D_NV">Nevada</option>

<option groupid="b" value="A_OR">Oregon</option>

<option groupid="c" value="B_WA">Washington</option>

<option groupid="a" value="C_AZ">Arizona</option>

<option groupid="b" value="D_CO">Colorado</option>

<option groupid="c" value="A_ID">Idaho</option>

<option groupid="a" value="B_MT">Montana</option>

<option groupid="b" value="C_NE">Nebraska</option>

<option groupid="c" value="D_NM">New Mexico</option>

<option groupid="a" value="A_ND">North Dakota</option>

<option groupid="b" value="B_UT">Utah</option>

<option groupid="c" value="C_WY">Wyoming</option>

</select>


Related Topics



Leave a reply



Submit