Reputation: 9037
I want to enable the button once user fill or type something on the input box and disabled it if user not fill or emptied the input box. Sadly, my snippet below is not working. Any help, suggestion, recommendation, ideas and clues is greatly appreciated.
$(document).ready(function(){
$("input").keypress(function(){
if($(this).val() !== ""){
//user fill or did type something on the input search box, lets enable the button
$("button").attr("disabled", false);
}else if($(this).val() === ""){
//user not fill or emptied the box, lets disabled the button
$("button").attr("disabled", true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_input" value="" placeholder="Type your search here" />
<button disabled>Go</button>
Upvotes: 0
Views: 118
Reputation: 2502
You can do that by setting the disabled attribute to true / false using the prop()
function.
$(document).ready(function() {
$("input").keyup(function() {
$("button").prop('disabled',$(this).val().length <= 0 );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_input" value="" placeholder="Type your search here" />
<button disabled>Go</button>
Upvotes: 1
Reputation: 9060
Seem like you missing braces. Working now.
$(document).ready(function() {
$("input").keyup(function() {
if ($(this).val() !== "") {
//user fill or did type something on the input search box, lets enable the button
$("button").prop("disabled", false);
} else if ($(this).val() === "") {
//user not fill or emptied the box, lets disabled the button
$("button").prop("disabled", true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_input" value="" placeholder="Type your search here" />
<button disabled>Go</button>
Upvotes: 1
Reputation: 17858
This works fine...
$(document).ready(function(){
$("input").keyup(function(){
if ($(this).val().length > 0){
$("button").attr("disabled", false);
}
else {
$("button").attr("disabled", true);
}
});
});
Upvotes: 1
Reputation: 1
Try utilizing input
, focus
events , for input
being focused while input
.length
not greater than 0
.
Note, Not certain about expected result if input
value multiple space characters ?
$(document).ready(function(){
$("input").on("input focus", function(){
if ($(this).val().length > 0) {
//user fill or did type something on the input search box, lets enable the button
$("button").prop("disabled", false);
} else {
//user not fill or emptied the box, lets disabled the button
$("button").prop("disabled", true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_input" value="" placeholder="Type your search here" />
<button disabled>Go</button>
Upvotes: 1