Reputation: 43
can anyone help me how to remove button disable attribute if the the textboxes with class(number
) have values inside and disable again if the textbox is empty.
current code:
<input type="text" name="name" class="number" value="hello" readonly />
<input type="submit" name="send" id="send" disabled />
script code:
<script type="text/javascript">
$('.number').on('input', function () {
$('#send').prop("disabled", !$.trim(this.value));
});
</script>
Upvotes: 0
Views: 1106
Reputation: 2290
try something like this
$('.number').on('change', function () {
if ($(this.val() == '') {
$('#send').removeAttr('disabled');
} else {
$('#send').attr('disabled', '');
}
});
Upvotes: 0
Reputation: 47956
You could listen for keydown
events and every time a key is pressed, you check the value of the element:
$( ".number" ).on( "keydown", function ( e ) {
var current_value = $( this ).val();
// The keypress event actually happens before the character is inserted.
var value = $.trim( current_value + e.which );
if ( value.length > 0 ){
$( "#send" ).attr( "disabled", false );
}
});
The only problem with this approach is that it will not work if the user copy-pastes a value into the textbox. The alternative would be to use a setInterval
to check the input every X seconds.
Upvotes: 0
Reputation: 371
Try it like this:
/* The keyup event fires right after the user releases a key */
$(".search-bar").on("keyup", function() {
var state = this.value === "";
$("#send").attr("disabled", state);
})
Upvotes: 0
Reputation: 128791
Your current code works fine: JSFiddle demo.
The problem is that your .number
element is set to readonly
, meaning it doesn't accept any input
(which is the event you're handling).
If you're setting the readonly
property on the server side, I imagine you can also set the disabled
property on the server side as well.
Upvotes: 1
Reputation: 82231
use:
$('.number').keyup(function() {
if($(this).val() != '') {
$('#send').removeAttr('disabled');
}else{
$('#send').attr('disabled',true);
}});
Upvotes: 2