Thursday, January 14

Disable Submit Button until Valid

The Case:
There are three search options, first name, last name or id number. You can search by any one (or more) but at least one has to be filled. I want to disable the submit button until one is filled, and have a little message that says you need to fill one.

The Javascript:

function searchVal(){

if(document.getElementById('fname').value.length == 0
&& document.getElementById('lname').value == 0
&& document.getElementById('datanum').value == 0){
dis = true;
}else dis = false;
if(dis == true){
document.getElementById('sub').disabled = true;
msg = 'At least one search field must be filled';
}else{
document.getElementById('sub').disabled = false;
msg = '';
}
document.getElementById('validmsg').innerHTML = msg;
}

function formVal(){
document.getElementById('sub').disabled = true;
document.getElementById('validmsg').innerHTML = 'At least one search field must be filled';

document.getElementById('fname').onchange = searchVal;
document.getElementById('lname').onchange = searchVal;
document.getElementById('num').onchange = searchVal;
}
The HTML:
<form action="results.php" class="pform" method="get">
<ol>
<li><label for="lname">Last Name</label><input type="text" name="lname" id="lname" /></li>
<li><label for="fname">First Name</label><input type="text" name="fname" id="fname" /></li>
<li><label for="num">ID Number</label><input type="text" name="num" id="num" /></li>
<li id="validmsg"></li>
<li><label for="submit"></label><input type="submit" name="sub" id="sub" value="Search" /></li>
</ol>

Other Comments:
The form items are in a list to look pretty as suggested by this ALA Article. The js is two functions because I'm using this handy dandy window onload manager.

Maybe tomorrow I'll be able to figure out how to check that the ID number is numeric.

Note: I found out later that even though the button is disabled, you can still submit the form using Enter.

No comments: