Struggling to create a new user POST form with Bootstrap form validation but encountering an issue. The button code is as follows:
<button class="btn btn-primary btn-addUser" type="submit">Add User</button>
This button triggers the creation of a new post using input data:
const addUsersBtn = document.querySelector(".btn-addUser");
// Handle click event for button
addUsersBtn.addEventListener("click", postNewUser);
// Function to perform POST request for new user
function postNewUser(e) {
e.preventDefault();
// Retrieve values from form inputs
const name = form.elements.namedItem("name").value;
const username = form.elements.namedItem("username").value;
const email = form.elements.namedItem("email").value;
const phone = form.elements.namedItem("phone").value;
const website = form.elements.namedItem("website").value;
// Create user object with input values
const newPost = {
name: name,
username: username,
email: email,
phone: phone,
website: website,
user_id: `id_${Math.random() * Math.random()}`,
};
// Make API call to create a new post
createPost(newPost, (response) => {
const card = newPostTemplate(response);
container.insertAdjacentElement("afterbegin", card);
form.reset();
initPopovers();
});
}
The validation does not work when 'btn-addUser' class is present on the button. Removing this class allows validation to function normally. My addUser.js file contains:
// Get form element
const form = document.forms["addUser"];
// Function to create a new post
function createPost(body, callback) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open("POST", "https://jsonplaceholder.typicode.com/posts");
request.addEventListener("load", () => {
const response = JSON.parse(request.responseText);
if (request.status >= 400) {
reject(request.response);
} else {
resolve(request.response);
}
callback(response);
});
request.setRequestHeader("Content-type", "application/json; charset=UTF-8");
request.send(JSON.stringify(body));
});
}
// Template for creating a new post
function newPostTemplate(post) {
// Code omitted for brevity
}
// Add event listener to button for adding users
addUsersBtn.addEventListener("click", postNewUser);
// Function to handle user submission
function postNewUser(e) {
// Code omitted for brevity
}
Questions:
- Is it possible to have two buttons, one with 'btn-addUser' class and one without? I want the button without the class to be disabled until successful validation, while the other button will automatically disable after clicking.
- Am I overcomplicating things and is there a simpler way to achieve this?