Reputation: 167
I have one simple form which have two fields called first name with id fname and email field with email. I have submit button with id called submit-btn. I have disabled submit button using javascript like this
document.getElementById("submit-btn").disabled = true;
Now I am looking for allow submit if both of my fields are filled.
My full javascript is like this
<script type="text/javascript">
document.getElementById("submit-btn").disabled = true;
document.getElementById("submit-btn").onclick = function(){
window.open("https://google.com",'_blank');
}
</script>
I am learning javascript and does not know how I can do it. Let me know if someone here can help me for same. Thanks!
Upvotes: 1
Views: 1481
Reputation: 2255
This is the simplest solution I can imagine:
myForm.oninput = () => {
btn.disabled = fname.value == '' || email.value == '' || !email.checkValidity();
}
<form id="myForm">
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="btn" value="Submit" disabled>
</form>
Personally, I prefer to use regex to check the e-mail, instead of checkValidity()
. Something like this:
/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(email.value);
Upvotes: 0
Reputation: 33449
Id propose something like this
addEventListener
over onclick
or onanything
input
s: input
and change
. input
will react on every keystroke, check
will only react, if you blur the input
elementcheckValidity
method
{
const btn = document.getElementById("submit-btn");
const fname = document.getElementById("fname");
const email = document.getElementById("email");
deactivate()
function activate() {
btn.disabled = false;
}
function deactivate() {
btn.disabled = true;
}
function check() {
if (fname.value != '' && email.value != '' && email.checkValidity()) {
activate()
} else {
deactivate()
}
}
btn.addEventListener('click', function(e) {
alert('submit')
})
fname.addEventListener('input', check)
email.addEventListener('input', check)
}
<form>
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="submit-btn" value="Submit">
</form>
Upvotes: 2