I'm definitly not a javascript hero at all so I have a question.
I have the below code in a external script and when the condition is true the message echo's to the login screen (this works fine). As a test I want the submit button to be disabled too, but how to achieve that? The ID of the button is "btn_input"
if(txtboxval == "" || emailboxval == "")
{
document.getElementById("announcement").innerHTML="This is a text!";
return;
}
Is this possible?
CodePudding user response:
//disable the button
document.getElementById(BUTTON_ID).disabled = true;
//reable the button
document.getElementById(BUTTON_ID).removeAttribute('disabled');
CodePudding user response:
Wow that's lightning fast, I will try this out guy's, thanks so much.
CodePudding user response:
If you want to imperatively disable the submit button, you can listen to changes on the form and evaluate the result of the checkValidity()
method.
const formDataToObject = (formData) => {
const result = {};
for (const [key, value] of formData) {
Object.assign(result, { [key]: value });
}
return result;
};
const onSubmit = (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const data = formDataToObject(formData);
alert(JSON.stringify(data, null, 2));
};
const onFormInput = (e) => {
// When restting, the form validation passes before the clear happens
// Let's wait 0.1 seconds and then set disabled
setTimeout(() => {
const form = e.target.closest('form');
const submitButton = form.querySelector('button[type="submit"]');
if (form.checkValidity()) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', '');
}
}, 100);
};
document.forms.login
.addEventListener('input', onFormInput);
document.forms.login.querySelector('button[type="reset"]')
.addEventListener('click', onFormInput);
html, body { width: 100%; height: 100%; margin: 0; }
body { display: flex; flex-direction: column; justify-content: center; align-items: center; }
form { display: grid; grid-template-columns: auto auto; grid-column-gap: 1rem; grid-row-gap: 0.5rem; }
form .actions { grid-column: 1 / 3; display: flex; justify-content: center; gap: 0.5rem; }
<form name="login" onsubmit="onSubmit(event)">
<label for="username-id">Username</label>
<input type="text" id="username-id" name="username" required />
<label for="password-id">Password</label>
<input type="password" id="password-id" name="password" required />
<div >
<button type="reset">Reset</button>
<button type="submit" disabled>Submit</button>
</div>
</form>