0

I have a textbox and a button. The functionality is that whenever textbox is empty, button is disabled and if not empty then button is enabled. I am doing this using following jQuery code:

$('#user_field').keyup(function(){
if($(this).val().length !=0){
    $('#btn_disabled').removeAttr('disabled'); 
    $('#btn_disabled').attr('class', 'upload_button_active');
}
else{
    $('#btn_disabled').attr('disabled',true);
    $('#btn_disabled').attr('class','upload_button_inactive');
       
}
})   

However, when I am trying to paste input using mouse, the button is not enabling. I have tried binding other mouse events like mousemove, but for that to work we have to move the mouse after pasting. I want to avoid that. Suggest something else.

See image here

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
bob
  • 547
  • 5
  • 14

3 Answers3

0

You should use 'input'

$("#tbx").on('input',function(){
  var tbxVal=$(this).val();
  if(tbxVal.length===0){
    $("#btn").prop("disabled",true);
  }else{
    $("#btn").prop("disabled",false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tbx">
<button id="btn" disabled>Button</button>
0

You can use the paste event and retrieve the value of the input inside a setTimeout

$('#user_field').on('paste input', function() {
  setTimeout(() => {
    if ($(this).val().length !== 0) {
      $('#btn_disabled').removeAttr('disabled');
      $('#btn_disabled').attr('class', 'upload_button_active');
    } else {
      $('#btn_disabled').attr('disabled', true);
      $('#btn_disabled').attr('class', 'upload_button_inactive');

    }
  }, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='user_field'>
<button id='btn_disabled' disabled='disabled'>Click</button>
brk
  • 43,022
  • 4
  • 37
  • 61
0

Just Call the function on change. It will take your input event from mouse as well.

$("#textBox").change(function(
 var val=$(this).val();
  if(val.length===0){
  $("#btn").prop("disabled",true);
 }else{
  $("#btn").prop("disabled",false);
 }
});