Reputation: 91
I want to be able to have a texbox enabled only when their is text written inside a certain textarea.
I tried using the onkeydown attribute for the textarea with a method I wrote. It works when I start typing (the button is enabled), but when I delete all the text and the textarea is empty, the button is still enabled.
//This is the html code for the textbox and textarea
<input type="text" id="testUser" disabled="disabled" placeholder="username">
<textarea rows="15" cols="105" id="sql" onkeydown="enableUsername()">
//This is the Javascript method I wrote
function enableUsername(){
var ele = document.getElementById("sql").value;
//document.getElementById("sql").value=+ele.length;
var flag = 0;
if(ele.length>0){
document.getElementById("testUser").disabled=false;
}
else{
document.getElementById("testUser").disabled=true;
}
}
If possible I would rather not have to use the onkeydown attribute for the textarea because I have another functionality I would like to implement later.
Upvotes: 0
Views: 72
Reputation:
Just replace onkeydown
by onkeyup
.
<input type="text" id="testUser" disabled="disabled" placeholder="username">
<textarea rows="15" cols="105" id="sql"></textarea>
var ele = document.getElementById("sql");
function enableUsername() {
var flag = 0;
if (ele.value.length > 0){
document.getElementById("testUser").disabled=false;
} else{
document.getElementById("testUser").disabled=true;
}
}
ele.addEventListener("keyup", enableUsername, false);
Upvotes: 0
Reputation: 1435
You can find a working snippet below -
var txtarea = document.getElementById('sql');
var username = document.getElementById('testUser');
function enableUsername() {
if (txtarea.value.length > 0) {
username.disabled = false;
} else {
username.disabled = true;
}
}
<input type="text" id="testUser" disabled="true" placeholder="username" />
<textarea rows="15" cols="105" id="sql" onkeydown="enableUsername()"></textarea>
Upvotes: 1