skip to Main Content

Here in this code I’m trying to disable the upload button when input is entered in text-box & when the text-box is empty upload button should be enabled, but here I’m doing exactly opposite to my desired results, it enables the button when input is provided and disables the button when no input is provided.

JS

<script>
    $(document).ready(function () {
      $("#textbx").keypress(function () {
        if ($("#textbx").val().length > 0) {
          $("#myFile").attr("disabled");
        }
      });

      $("#textbx").blur(function () {
        if ($("#textbx").val().length == 0) {
          $("#myFile").attr("disabled", "disabled");
        }
      });
    });
  </script>

HTML

<input id="textbx" type="text" />
      <input type="file" id="myFile" name="filename" />

2

Answers


  1. set disabled to true to deactivate and false to reactivate

    am using jQuery v3.6.3 in this example

    $(document).ready(function () {
      $("#textbx").on('keyup', function () {
        if ($("#textbx").val().length > 0) {
          $("#myFile").attr("disabled", true);
        } else {
           $("#myFile").attr("disabled", false);
        }
      });
    });
    <input id="textbx" type="text" />
    <input type="file" id="myFile" name="filename" />
    
    <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
    Login or Signup to reply.
  2. $("#textbx").on('keyup', function () {
        if ($("#textbx").val().length > 0) {
          $("#myFile").attr("disabled", 'disabled');
        } else {
           $("#myFile").removeAttr("disabled");
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input id="textbx" type="text" />
    <input type="file" id="myFile" name="filename" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search