Form validation script issue (onclick event handler not working)


<!DOCTYPE html>

<html>
	<head>
		<title>form</title>
		
		<script>
/*		
function required()
{
    var empt = document.forms["contact"]["Name"].value;
    if (empt == "")
    {
        alert("Please input a Value");
        return false;
    }
}

*/

function required()
{
var x = document.getElementsByTagName("input");

	if (x == "")
    {
	alert("Please input a value");
	return false;
    }
}
		
		</script>	

	</head>
	<body>
		<form action="http://www.example.com/subscribe.php" name="contact">
			<fieldset>
				<legend>Contact details</legend>
				<label>Email:<br /><input type="text" name="email" /></label><br />
				<label>Mobile:<br /><input type="text" name="mobile" /></label><br />
				<label>Telephone:<br /><input type="text" name="telephone" /></label><br />
				<input type="submit" value="enter" onclick="required()" />
			</fieldset>
		</form>
	</body>
</html>


Scratching my head on this one.

I’m trying to test each input field and i’m not sure what the best to do this is.

I tried this but it didn’t do anything. where did i go wrong.

how could do this with a for loop or some other control structure?


var errors = new Array();
for(var i = 0;i<=x.length;i++){
    if(x[i].value == "") {
        errors.push(x[i].name);
    }
}

if(errors.length > 0) alert('Please fill in the following fields' + errors);

Not 100% sure if you’d get the element name in that way, but that should get you started.

Note that the only use remaining for alert() is as a placeholder for code not yet written. It became obsolete in live scripts when Netscape 4 died and became unnecessary for debugging when Firefox 19 was released with a built in debugger (the last browser to not have one built in).

Also 99.999%+ of JavaScript work best when placed immediately before the </body> tag.

Also you should not be using onclick on the submit button you should be using onsubmit on the form tag. It should also not be jumbled with the HTML but should instead be attached from within the JavaScript.