user14361363
user14361363

Reputation:

How to disable html button if input is empty?

I am using a modal from bootstrap to allow users to post comments on my website. Everything is okay except that the user can post a comment if the input is null. I want to disable the button if the input is null

This is the button modal from bootstrap

<button
  type="button"
  class="btn btn-dark"
  data-bs-toggle="modal"
  data-bs-target="#exampleModal"
  id="addComment"
>
  Add a comment
</button>

<!-- Modal -->
<div
  class="modal fade"
  id="exampleModal"
  tabindex="-1"
  aria-labelledby="exampleModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add a comment</h5>
      </div>
      <div class="modal-body">
        <div class="input-group mb-3">
          <input
            type="text"
            class="form-control"
            placeholder="Name"
            id="name"
            aria-describedby="basic-addon1"
          />
        </div>
        <div class="input-group mb-3">
          <input
            type="text"
            class="form-control"
            placeholder="Comment"
            id="comment"
            aria-describedby="basic-addon1"
          />
        </div>
      </div>
      <div class="modal-footer">
        <button
          type="button"
          class="btn btn-light"
          data-bs-dismiss="modal"
        >
          Cancel
        </button>
        <button
          type="button"
          class="btn btn-dark"
          data-bs-dismiss="modal"
          id="postButton"
          onclick="postComment()"
        >
          Comment
        </button>
      </div>
    </div>
  </div>
</div>

What have I tried?

  1. I tried loading the Dom and then add event listener to the "add comment" button and watch for input changes such as:

    document.addEventListener("DOMContentLoaded", () => {
      var addbutton = document.getElementById("addComment");
      addbutton.addEventListener("click", () => {
        var name = document.getElementById("name");
        name.addEventListener("change", () => {
          if (name.value.length > 0) {
            document.getElementById("postButton").disabled = false;
          } else {
            document.getElementById("postButton").disabled = true;
          }
        });
      });
    });
    
  2. I googled if there is a required field in bootstrap and even added required to both inputs but this didn't work.

  3. I've also tried setting the button attribute disabled and work with above code but didn't work

I've tried more things but they didn't quite work. As I mentioned above, I need to disable the html button if the input is null. Any help is appreciated.

P.S I'm first trying on a single input then I will work on both

Upvotes: 4

Views: 4052

Answers (3)

Scott Marcus
Scott Marcus

Reputation: 65806

Your attempt sets the event handler on name when the click event happens on the button and all of that is set up in a handler for DOMContentLoaded. This can be simplified greatly.

If you move your script so that it is positioned just prior to the closing body tag, you won't need to nest your code inside of a DOMConentLoaded event handler because by the time the parser reaches this point, the DOM will be loaded. Next, you just need to set up a blur event handler (which fires when a field loses the focus) or the input event (which fires every time the the field receives any input to its 'value') that checks to see if the element has content and enables/disables the button accordingly.

Here's an example:

<!DOCTYPE html>
<html>
<head>
  <title>Enable/Disable submit</title>
</head>
<body>

  <input id="one"><input id="two"><button disabled>Submit</button>

  <!-- By placing the script just before the closing
       body tag, you ensure that all the other elements
       have been parsed into memory when the script runs. -->
  <script>
    const input1 = document.querySelector("#one");  
    const input2 = document.querySelector("#two");    
    const btn = document.querySelector("button");
    
    // Use the same validation handler for both inputs
    input1.addEventListener("input", validate);
    input2.addEventListener("input", validate);    
    
    function validate(){
      // Check that neither input is empty
      if(input1.value === "" || input2.value === ""){
        btn.setAttribute("disabled","disabled");
      } else {
        btn.removeAttribute("disabled");  
      }
    }    
  </script>
</body>
</html>

Upvotes: 2

Countour-Integral
Countour-Integral

Reputation: 1154

A few things you have wrong here.

  • You have an event listener inside an event listener

Each time addbutton is clicked you assign a new event listener to name which is redundant. You have to move name.addEventListener outside.

let name = document.getElementById("name");

name.addEventListener("input", () => { // Also using `input` instead of `change`
    if (name.value.length > 0) {
      document.getElementById("postButton").disabled = false;
    } else {
      document.getElementById("postButton").disabled = true;
    }
});

Notice something different here as well? Instead of using "change" I've used "input" because it makes changes in real time (when you type), while "change" gets triggered when you focus outside of the input.

Now when the document is loaded you have to disable the button and you will be set.

Also instead of using the old style onLoad event listeners you put your script after the HTML and then you can attach a defer to your script like this.

<script defer>
// Your Javascript will be executed
// after all the html has been loaded
</script>

let name = document.getElementById("name");
let postButton = document.getElementById("postButton");
postButton.disabled = true;
name.addEventListener("input", () => {
    if (name.value.length > 0) {
      postButton.disabled = false;
    } else {
      postButton.disabled = true;
    }
});
<button
  type="button"
  class="btn btn-dark"
  data-bs-toggle="modal"
  data-bs-target="#exampleModal"
  id="addComment"
>
  Add a comment
</button>

<!-- Modal -->
<div
  class="modal fade"
  id="exampleModal"
  tabindex="-1"
  aria-labelledby="exampleModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add a comment</h5>
      </div>
      <div class="modal-body">
        <div class="input-group mb-3">
          <input
            type="text"
            class="form-control"
            placeholder="Name"
            id="name"
            aria-describedby="basic-addon1"
          />
        </div>
        <div class="input-group mb-3">
          <input
            type="text"
            class="form-control"
            placeholder="Comment"
            id="comment"
            aria-describedby="basic-addon1"
          />
        </div>
      </div>
      <div class="modal-footer">
        <button
          type="button"
          class="btn btn-light"
          data-bs-dismiss="modal"
        >
          Cancel
        </button>
        <button
          type="button"
          class="btn btn-dark"
          data-bs-dismiss="modal"
          id="postButton"
          onclick="postComment()"
        >
          Comment
        </button>
      </div>
    </div>
  </div>
</div>

Upvotes: 0

Dbw
Dbw

Reputation: 1

Try making the input required

<input type="text"> ===> <input type="text" required>

However, it think if someone changes the tag they can enter in nothing. In that case just check for posts with a value of nothing and prevent them from being put in the db.

Upvotes: 0

Related Questions