3

I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)

It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.

My code looks like this:

<form action="database.php" method = post>

    Username 
    <input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
    <div id="name"></div><br>
    .....
</form>

And the Javascript:

<script type="text/javascript">
function checkname() {
    var name = document.getElementById("un").value;
    var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;

    if (name.search(pattern) == -1) {
        document.getElementById("name").innerHTML = "wrong";
    }
    else {
        document.getElementById("name").innerHTML = "right!";
    }
}

function checkempty(id) {
    var temp = document.getElementById(id).value;

    if (!temp) {
        document.getElementById("name").innerHTML = '';
    }
}
</script>
Chad
  • 19,219
  • 4
  • 50
  • 73
Sam
  • 2,309
  • 9
  • 38
  • 53
  • `It simply isn't working the way I intended` - Can you elaborate? – James Hill Nov 28 '11 at 19:07
  • Well when I delete the input field fully, the div message does not change, which theoretically should since it should be checking every keystroke, right? – Sam Nov 28 '11 at 19:09

2 Answers2

0

This function should below should check for empty field;

 function checkempty(id) {
   var temp = document.getElementById(id).value;
   if(temp === '' || temp.length ===0){
     alert('The field is empty');
     return;


   }


 }

//This should work for check name function

  function checkname() {
   var name = document.getElementById("un").value;
   var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;

   if (!name.test(pattern)) {
    document.getElementById("name").innerHTML = "wrong";
   }
   else {
    document.getElementById("name").innerHTML = "right!";
  }
}
EBIWARI
  • 43
  • 1
  • 6
0

Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.

Here's a working fiddle.

Edit: See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key

Community
  • 1
  • 1
James Hill
  • 60,353
  • 20
  • 145
  • 161