4

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

2
  • Where is postComment defined? The thing that is called when the button "Comment" is pressed. You should probably be checking there if the length of the input > 0. Commented Jan 11, 2021 at 23:27
  • I want to disable the button if the inputs are null not when I press the button Commented Jan 11, 2021 at 23:28

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

The problem is if the the first input is not null but the second is null, the user can post a comment. That means that the first input can be submitted alone but not the second
@NabilTheCoder Check out the updated answer. It's just a matter of having both inputs use the same handler and having the handler check both inputs.
Thank you so much, I was really tired and you helped me. Just curious about using getElementById and querySelector. Which is better?
@NabilTheCoder You're welcome (don't forget to up vote and mark as the answer). There's not a lot of difference between getElementById and querySelector although technically, getElementById could be slightly faster due to how browsers store ids, but in modern applications, you wouldn't be able to notice such a small difference.
0

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.

Comments

0

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>

2 Comments

Try your code snippet. it will best explain my problem
Thanks man I got the idea. You got an upvote

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.