Forum Moderators: open
//html-the old way
function checkForm(){
var myForm = docoument.form1
if (myForm.txtAge.value =="" || myForm.txtName.value =="")
{
alert("Please complete all the form.");
if (myForm.txtName.value =="")
{
myForm.txtName.focus();
}
else
{
myForm.txtAge.focus();
}
.
.
etc...
}
<form name="form1">
<input type="button" onclick="checkForm()" />
//xhtml-conversion
function checkForm(){
var myForm = docoument.forms["form1"] <----- not working? but you get the idea?
.
.
.
}
<form id="form1">
<input type="button" onclick="checkForm()" />
// I left in a reference to the form in this example,
// but WE'RE NOT EVEN USING IT. Note how it's passed
// via the onsubmit handler - but we don't need it for
// what we're doing here.
function checkForm(form){
// Just an example of using the form parameter.
// You could refer to fields as form.txtAge, etc.
// if you wanted to.
var required = {
'txtAge':'Age',
'txtName':Name',
'some-other-field':'Other Value'
};
var msg = '';
for (key in required) {
if (documentGetElementById(key).value=='') {
msg += "The " + required[key] + " field is required.\n";
}
if (msg=='') { return true; }
else { alert(msg); return false; }
}
<html>
<head><title></title>
<script type="text/javascript">
function checkForm()
{
//creates an array-like object
var required = {
'txtName' : 'Name',
'txtAge' : 'Age'
}
var msg='';
//sweeps the required object
for (key in required)
{
if (document.getElementById(key).value=='')
{
msg += "The " + required[key] + " field is required.\n";
}
}
if(msg=='')
{
//isNAN sucks
x = parseFloat(document.form1.txtAge.value)
if (x*0!==0)
{
msg += "Please enter a valid age";
document.form1.txtAge.focus();
document.form1.txtAge.select();
}
}
//submits to server on true; not on false
if(msg=='') {return true;}
else {alert(msg); return false;}
}
</script>
</head>
<body>
<!-- default method attribute value is 'get' -->
<form name="form1" id="form1" onsubmit="return checkForm();">
<p><label for="txtName">Name:</label><input type="text" id="txtName" name="txtName" /></p>
<p><label for="txtAge">Age:</label><input type="text" id="txtAge" name="txtAge" size=3 maxlength=3 /></p>
<input type="submit" value="submit" />
</form>
</body>
</html>
<?php
if (isset($_SERVER['HTTP_ACCEPT']))
{
$mime = stristr($_SERVER['HTTP_ACCEPT'],'application/xhtml+xml');
}
else {$mime = 'text/html';}
if ($mime) {$mime = 'application/xhtml+xml';}
else {$mime = 'text/html';}
header('Content-Type: '.$mime);
?>
<div><pre>
<?php
print_r($_POST);
?>
</pre></div>
<div><label for="form_id_1">Label Text</label><input id="form_id_1" name="form_id_1" type="text" value="" /></div>
alert(document.getElementById('form_id_1').value);
var a = document.getElementById('form_id_1');
alert(a.value);
//change form value? Use object directly...
document.getElementById('form_id_1').value = 'oh hai!';
var a = document.getElementById('form_id_1');
alert(typeof a.value);
There simply is no reason to use HTML and text/html.