0
Help pls how can I do this.
For example I have a form. And I put this code (JavaScript) function submit(){ document.write("Thanks") console.log("Thanks for applying") } window.onload = function(){ let btn = document.getElementById ("hover") btn.onclick = submit } At the submit button. How can I let the code not to be run if it is was not filled correctly
4 Respostas
+ 4
You can wrap all the form's inputs and the submit button inside a <form> tag so that it is easier to make the script find all needed inputs.
Then, there are several ways to validate the form.
One of them is using Validation API (reference: https://www.w3schools.com/js/js_validation_api.asp ) along with validating attributes of the <input> tags (reference: https://www.w3schools.com/html/html_form_attributes.asp ). I see it as the easiest to implement. {1}
Amother way would be to manually get each <input> and check them for validity using the rules you write for each <input>. In this case, you would like to use a Boolean variable that is set to true at first and gets set to false if there is an invalid input.
{1}
function sublit(){
let form = document.getElementsByTagName ("form")[0]
if(form.checkValidity()){
document.write("Thanks")
console.log("Thanks for applying")
}
else{
console.log(form.validationMessage)
}
}
+ 4
Another reference that would be helpful during implementing the first way: https://developer.mozilla.org/ru/docs/Web/API/HTMLFormElement#htmlformelement.checkvalidity , https://developer.mozilla.org/en-US/docs/Web/API/Constraint_validation , https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input .
+ 1
Thanks
0
HTML:
<form autocomplete=“off”>
<!—your html—>
<input id=“idk” required></input