First, there is no such method as getElementsById()
, it's getElementById()
, which returns one element (if found). So there is no array returned from it, so passing an index isn't going to get you anything.
Next, your inline event attribute has to provide executable code that would invoke your function, but you didn't put parenthesis after the function name, so your code doesn't do this. But, you should not be using inline HTML event attributes in the first place. Instead, do all your event binding in JavaScript with the standard addEventListener()
method, which actually does take a callback method reference (no parenthesis).
Now, it appears that you just want the input to have a placeholder that matches the selected item from the list, in which case, you don't need an if
statement for that, just set the placeholder
to the selected value directly. You only need the if
to detect if the first item was selected and in that case, use the setAttribute
method to set up the disabled functionality.
Also, since the select's first option is DOC
and that choice should make the input
disabled, you should add the disabled
attribute to the input
HTML statically from the start.
See the comments below for more adjustments.
// Get references to elements you'll work with just once, not upon
// each invocation of the event handler. Also, don't name or give things
// id's that are also the name of an object (ie. document)
let select = document.getElementById("list");
let input = document.getElementById("docu");
// Set up the event handler in JavaScript, not with HTML attributes like onchange
select.addEventListener("change", changeDOC);
function changeDOC() {
input.placeholder = this.value; // `this` is a reference to the select itself
if (this.value == "doc") {
input.setAttribute("disabled", "disabled");
} else {
input.removeAttribute("disabled");
}
}
<select id="list">
<option value="doc" selected>DOC</option>
<option value="cpf">CPF</option>
<option value="cnpj">CNPJ</option>
</select>
<input type="text" class="form-control" id="docu" placeholder="Select a document." disabled>