Ok, what I am trying to do are several things:
(also I'm a JS newbie, so I'm still struggling how to have a function implemented that does that all that ... you do use a function for this, correct?
Here's an earlier form of mine ... I am really struggling to implement those three characteristics listed above ... how do I implement those in the code beneath? Thanks in advance.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Testy Form</title>
</head>
<body>
<h4>Learning to Validate Forms</h4>
<div id="validationErrors"></div>
<form action="" method="post" id="testyForm">
<label>Name
<input type="text" name="name" value="" id="name">
</label>
<br /><br />
<label>Email
<input type="text" name="email" value="" id="email">
</label>
<br /><br />
<input type="submit" value="Submit">
</form>
<script>
var formy = document.getElementById('testyForm');
var required_inputs = ['name', 'email'];
formy.onsubmit = function(event) {
for (var i = 0; i < required_inputs.length; i++) {
var input = this[required_inputs[i]];
if (input.value.length == 0) {
event.preventDefault();
input.style.border = "1px solid red";
input.style.backgroundColor = "#FFCCCC";
}
}
}
</script>
</body>
</html>
if you are just trying to get things work, I would suggest using a validation library instead of writing your own.
if you are learning Javascript, here's the error in your code:
update
var input = this[required_inputs[i]];
to
var input = document.getElementById(required_inputs[i]);
you declared required_inputs as an array:
var required_inputs = ['name', 'email'];
and when you loop through it, required_inputs[i]
will return 'name'
and 'email'
so that can be used as the parameter of getElementById()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.