0

I need to enable/disable a button based on a input field. If the input field has a value, the button should be enabled. If the input field is empty, the button should be disabled. Now when the user selects a value from the input field cookie, How do I capture? I tried with "change" but it didn't work.

The tried the below code with "change" event:

<script>
$(function() {
$("#myInput").change(showSaveBtn);

var showSaveBtn = function() {
            validateInput();
            if (myInputEntered== true) {
                $('#save').removeClass("disabled").prop(
                        'disabled', "disabled").removeAttr("disabled");
            } else {
                $('#save').addClass("disabled").prop(
                        'disabled', "disabled");
            }
        }

var validateInput= function() {
            if ($.trim($("#myInput").val()) === '')
                myInputEntered= false;
            else
                myInputEntered= true;
        }
});
</script>

Based on #myInput value, I need to enable/ disable #save button. Looking forward for the answers.

thanks, Iswarya

Charlie
  • 22,886
  • 11
  • 59
  • 90

2 Answers2

0

It is very likely that by the time you hook the event, the DOM element was not loaded. You need to wait until the DOM is loaded to hook the events.

$(document).ready(function(){

 
  var inputChanged = function() {

     
     var myInputEntered = validateInput();
     console.log(myInputEntered);
            
     if (!myInputEntered)
        $('#save').hide()
     else 
        $('#save').show();
          
  }

  var validateInput= function() {
     return $.trim($("#myInput").val()) !== ''
  }
  
  
  $("#myInput").keyup(inputChanged);


  inputChanged();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="myInput">

<input type="button" value="save" id="save">
Charlie
  • 22,886
  • 11
  • 59
  • 90
0

 $("#save").prop('disabled', true);
    $("#myinput").on('change keydown paste input propertychange click keyup blur', function(){
    $("#save").prop('disabled', $('#myinput').val().length>0? false:true);
})
<input type="text" id="myinput">

<button id="save">
save
</button> 



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

you can write it like this too. hope this will help you. here is jsfiddle link

CodeBug
  • 1,649
  • 1
  • 8
  • 23