简体   繁体   中英

Select box disable self on select

i want to disable a select box, when user select something. Javascript code:

function desabilitar(val) {
    $(val).attr('disabled','disabled');
}

HTML:

<select class="form-control" onchange="desabilitar('mes')"  id="mes" name="mes">

But is not working... Any help?

You should use prop and not attr , and make sure you select the attribute by the id using '#':

Example:

 function desabilitar(val) { $('#'+val).prop('disabled', true); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="form-control" onchange="desabilitar('mes')" id="mes" name="mes"> <option>123</option> <option>456</option> </select> 

Try this:

function desabilitar(val) {
 document.getElementById(val).disabled = true;
}

The same with jQuery:

function desabilitar(val) {
  $("#" + val).attr('disabled', 'disabled');
}

Do you want to use jQuery or JavaScript? In your question you are asking for JavaScript but you are using jQuery?

You need to add "#" + to before val . This will make sure you are looking for an element with the id that is val.

 function desabilitar(val) { $("#" + val).attr('disabled', 'disabled'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="form-control" onchange="desabilitar('mes')" id="mes" name="mes"> <option>Test 1</option> <option>Test 2</option> <option>Test 3</option> </select> 

You need to use a # to correctly get an element by its id and set the disabled attribute, like so:

function desabilitar(val) {
$("#"+val).attr('disabled','disabled');

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM