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?
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; } }); }); });I googled if there is a required field in bootstrap and even added
requiredto both inputs but this didn't work.I've also tried setting the button attribute
disabledand 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
postCommentdefined? The thing that is called when the button "Comment" is pressed. You should probably be checking there if the length of the input > 0.