Consider a suitable example:-
index.html:-
<html>
<head>
<body>
<form name="form1" onsubmit="return validator()" method="post">
Username: <input type="text" name="username"/> <br/> <br/>
Password: <input type="password" name="password"/> <br/> <br/>
<input type="radio" name="radio" id="radio">Radio button
<input type="checkbox" name="thebox"/>Check Box <br/> <br/>
<input type="submit" value="Submit!"/>
</form>
<script src="app.js">
</script>
</body>
</html>
index.html:-
<html>
<head>
<body>
<form name="form1" onsubmit="return validator()" method="post">
Username: <input type="text" name="username"/> <br/> <br/>
Password: <input type="password" name="password"/> <br/> <br/>
<input type="radio" name="radio" id="radio">Radio button
<input type="checkbox" name="thebox"/>Check Box <br/> <br/>
<input type="submit" value="Submit!"/>
</form>
<script src="app.js">
</script>
</body>
</html>
app.js:-
function validator()
{
if(!document.form1.thebox.checked || !document.getElementById("radio").checked ||
document.form1.username.value == "" || document.form1.password.value == "")
{
alert("Not entered");
}
else
{
alert("All elements are entered");
}
}
Output:-
Explanation:-
Here, under the <form> tag, all the elements of it, like textbox, radio button, checkbox are included. When we will click on the "submit" button, then the control will go to the function called "validator", declared in the "aap.js" file, due to the attribute called "onsubmit" declared in the form tag. "method" attribute is also being used here in the form tag, so that whatever values we are going to enter, it will not display in the url. For validation purpose, "name" attribute is used for username and password textbox. It has also been used for checkbox element. "id" attribute has been used for the radio button.
No comments:
Post a Comment