Search code examples
jqueryif-statementjquery-click-event

how to use if else statement for click event to check the input value is true or false


function event() {
   $('main').css("display", "none");
   $('section').css("display", "block");
}

function startButton(){
   if($('input').val() === true){
   $('button').on('click', event)
   } else if($('input').val() === false){
      $('button').off('click', event)
   }
}
startButton()

when I do if statement with if($('input').val() === "") the click event works whether the user typed text in input or not when I check the Boolean on console it returns true or false depending on the input value is filled or not

I would like to add click event on the button when the user types in the input and remove the click event when there is no text written in the input

can someone help me with my code?


Solution

  • My answer is similar to the other from object reference.

    But the event handler won't be registered many times.

    // The function to execute on button click
    function event(){
      $('main').css("display", "none");
      $('section').css("display", "block");
    });
    
    // The input check
    $('input').on("input",function(){
      if(($this).val()!=""){
        $('button').off('click', event).on('click', event); // Off then on to prevent the handler to be registered multiple times.
      }else{
        $('button').off('click', event);
      }
    });
    

    Alternatively... And this is probably the best way to do it:

    $("button").on("click",function(){
      $('main').css("display", "none");
      $('section').css("display", "block");
    });
    
    $('input').on("input",function(){
      if(($this).val()!=""){
        $('button').prop("disabled",false);
      }else{
        $('button').prop("disabled",true);
      }
    });
    

    Add the "disabled" attribute in your button markup for the onload state:

    <button disabled>whatever</button>