Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable button whenever a text field is empty dynamically

Here's my code:

<input type="text" onkeyup="if(this.value.length > 0) document.getElementById('start_button').disabled = false; else document.getElementById('start_button').disabled = true;"/>
<input type="button" value="Click to begin!" id="start_button" disabled/>

This works but still not efficient since the user can delete the text inside the text box and click the button while he's holding on DELETE key. Is there a more efficient way to achieve this using javascript?

like image 534
Eng.Fouad Avatar asked Aug 15 '11 15:08

Eng.Fouad


2 Answers

Easiest way to do it :-

Simple Html and JavaScript : Run the snippet (Just 7 lines)

function success() {
	 if(document.getElementById("textsend").value==="") { 
            document.getElementById('button').disabled = true; 
        } else { 
            document.getElementById('button').disabled = false;
        }
    }
<textarea class="input" id="textsend" onkeyup="success()" name="demo" placeholder="Enter your Message..."></textarea>
<button type="submit" id="button" disabled>Send</button>

I have used textarea, but you can use any html input tags and try it out! Happy coding!

like image 81
Harish Kulkarni Avatar answered Sep 22 '22 06:09

Harish Kulkarni


Add a check when the button is clicked to see if there is any text. If there isn't, pop up an alert box (or some other form of feedback) to tell the user to enter data, and don't do the button functionality.

Example:

<input id="myText" type="text" onkeyup="stoppedTyping()">
<input type="button" value="Click to begin!" id="start_button" onclick="verify()" disabled/> 

<script type="text/javascript">
    function stoppedTyping(){
        if(this.value.length > 0) { 
            document.getElementById('start_button').disabled = false; 
        } else { 
            document.getElementById('start_button').disabled = true;
        }
    }
    function verify(){
        if myText is empty{
            alert "Put some text in there!"
            return
        }
        else{
            do button functionality
        }
    }
</script>
like image 21
yoozer8 Avatar answered Sep 18 '22 06:09

yoozer8