I'm trying to disable submit button if the user hasn't provided any text.
At first sight it looks that everything works just fine, but if user types some text, then deletes it, the submit button becomes enabled.
Here is my code:
$(document).ready(function(){ $('.sendButton').attr('disabled',true); $('#message').keyup(function(){ if($(this).val.length !=0){ $('.sendButton').attr('disabled', false); } }) });
1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.
To disable an input field inside a <Form /> function component, we will use isDisabled local state and it's setter method setIsDisabled , defined using the useState() hook.
Use the disabled prop to disable a button in React, e.g. <button disabled={true}>Click</button> . You can use the prop to conditionally disable the button based on the value of an input field or another variable or to prevent multiple clicks to the button. Copied!
You are disabling only on document.ready
and this happens only once when DOM
is ready but you need to disable
in keyup event too when textbox gets empty. Also change $(this).val.length
to $(this).val().length
$(document).ready(function(){ $('.sendButton').attr('disabled',true); $('#message').keyup(function(){ if($(this).val().length !=0) $('.sendButton').attr('disabled', false); else $('.sendButton').attr('disabled',true); }) });
Or you can use conditional operator instead of if statement. also use prop instead of attr as attribute is not recommended by jQuery 1.6 and above for disabled, checked etc.
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method, jQuery docs
$(document).ready(function(){ $('.sendButton').prop('disabled',true); $('#message').keyup(function(){ $('.sendButton').prop('disabled', this.value == "" ? true : false); }) });
Try this code
$(document).ready(function(){ $('.sendButton').attr('disabled',true); $('#message').keyup(function(){ if($(this).val().length !=0){ $('.sendButton').attr('disabled', false); } else { $('.sendButton').attr('disabled', true); } }) });
Check demo Fiddle
You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses ()
after val
function in if($(this).val.length !=0){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With