I have a form in which if a store has not been selected, it cannot write a reference, so I have it disabled, but the function does not perform the action.
<label for="warehouse">* Almacén</label>
<select id="warehouse_id" onChange="myDisFunction()">
... </select>
<label for="inventory_id">* Referencia</label>
<input type="text" id="inventory_id">
<script>
function myDisFunction() {
var x = document.getElementById("warehouse_id").value;
if(warehouse_id != null){
inventory_id.disabled =false;
}
}
</script>
Something simpler you could do it in the following way:
Several things:
input
should appear asdisabled
input
by its id, to enable it or not, which you don't do.selectedIndex
ofselect
to know if they have been selected or not. In the example code I have put aoption
by default to avoid confusion. This allows two things: uncheck an option that has been chosen by mistake, reverting to theoption
default one; and re-disable theinput
in that case. Both things will be very difficult if not impossible without thatoption
by default.Finally, I recommend that you avoid in-line functions, they are bad practice. It's best to assign listener events in the Javascript code, so your HTML is self-contained. Putting functions in-line means putting HTML Javascript code into context, violating the single responsibility principle.
Let's see an example using event listener:
What is the difference? We have removed the in-line call from HTML:
onChange="myDisFunction(this)"
, we don't need it, we are listening for changes to theselect
, by its id.What advantages does this have? I already said one: we respect the principle of single responsibility and we facilitate the maintenance of the code. Imagine a big project, with thousands of HTML in which you have put in-line calls. Now those in-line functions need another parameter or something like that. I want to see you, searching through the thousands of HTML to change this:
onChange="myDisFunction(this)"
to this:onChange="myDisFunction(this,ooootroParametro)"
.