Skip to content Skip to sidebar Skip to footer

JavaScript: Hide Button Link If Input Field Is Empty

I am trying to hide a button link (id='btnsubmit') whenever the input field (id='valagency') is empty, so that my user can only click on the button after the input field is filled

Solution 1:

You're calling function submit at that time your enable disable button code will execute.

you need to use that code independently not on submit call.

Place following code out of submit function:

$("#valagency").keyup(function(){
    if($(this).val() == "") {
        $("#btnsubmit").show();
    } else {
        $("#btnsubmit").hide();
    }
});

If you want to disable submit on submit button click how it's possible when you've used keyup event.

If you want to do so on submit button click then you need to use keyup.

If you want to use keyup then code will be outside of submit function.

Keyup will not work on pasting data to input. For that consider this example.

<input type="text" name ="mytxt" id="mytxt"> 
<a href="#" id="btnsubmit" class="btn1">Submit</a>


$('input[name=mytxt]').change(function() { 
if($(this).val() == "") {        
        $("#btnsubmit").hide();
    } else {
        $("#btnsubmit").show();
    }
});

If you want to hide button on page load then you can go with https://jsfiddle.net/kurbhatt/m06yywmn/2/


Solution 2:

The problem is that you're running your keyup() function on click of the submit button. This will never execute. Simply move your keyup() function outside of this button click. You'll also want to hide #btnsubmit by default.

Here's a minimal example:

$("#btnsubmit").hide();
$("#valagency").keyup(function() {
  if ($(this).val()) {
    $("#btnsubmit").show();
  } else {
    $("#btnsubmit").hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="valagency">
<a href="#" id="btnsubmit" class="btn1">Submit</a>

Hope this helps! :)


Solution 3:

Instead of keyup event, use change event to get the final value of input field and check for it's emptiness.


Solution 4:

It's just related with input keyup event, so If you want to check the input's value to hide/show the button. make it independent with 'submit', it should be hide/show before the 'submit'.

function submit() {
  //do something
}
$("#valagency").keyup(function(){
  if($(this).val() == "") {
      $("#btnsubmit").show();
  } else {
      $("#btnsubmit").hide();
  }
});

Post a Comment for "JavaScript: Hide Button Link If Input Field Is Empty"