I have a form with a Name, Email, and Text input as well as a Submit button. Clicking Submit checks the fields to make sure there’s text in them. If there’s text in the fields, clicking submit should submit the form info and change the text of the button to "Sent!"
For whatever reason I can’t figure out how to get the button text to change.
<div class="form-container">
<form action="/" class="form">
<div class="inner-form">
<h1>Contact Us</h1>
<input type="text" placeholder="Name" id="name-field" required>
<input type="email" placeholder="Email" id="email-field" required>
<textarea name="message" id="message-field" cols="30" rows="10"
placeholder="Let's hear your idea.." required></textarea>
<button class="form-button" type="submit" href="/">Submit</button>
</div>
</form>
</div>
const nameField = document.querySelector("#name-field").value;
const emailField = document.querySelector("#email-field").value;
const textField = document.querySelector("#message-field").value;
const form = document.querySelector(".form");
const formButton = document.querySelector(".form-button");
form.addEventListener("click", validateField);
function validateField(event) {
event.preventDefault();
if (nameField === "") {
$('#name-field').attr('placeholder', 'Please enter your name.');
$('#name-field').addClass('needText');
}
if (emailField === "") {
$('#email-field').attr('placeholder', 'Please enter your email.');
$('#email-field').addClass('needText');
}
if (textField === "") {
$('#message-field').attr('placeholder', 'Please enter your message.');
$('#message-field').addClass('needText');
} else {
formButton.innerText = "Sent!";
}
}
2
Answers
You need to extract the validation logic from the logic to show feedback to the user. They’ll be handled separately.
You can do this by rechecking all values together with OR operators, or just use a variable to track it.
That said, I’d encourage you to look into modern HTML5 form validation. You can automate some of the things you’re doing here with the
required
input attribute and form validity properties.const nameField = document.querySelector("#name-field").value;
Your Selection are selected only value of this DOM element, You can try this way