Anonymous the Great
Anonymous the Great

Reputation: 1669

How do I detect when an input is changed?

Via JavaScript, PHP, or HTML. I want to do this to check if a username is allowed (on our side).

Sorry for not elaborating too much. If the username is too short, a message will appear next to it (I will do this part) saying that it is too short, but for this to be done automatically I would need for it to be detected.

<script type="text/javascript">
document.getElementById('username').onchange=userCheck;
function userCheck() {
    document.getElementById("usercheck").innerHTML="kk";
}
</script>

<form action="devlabs.php">
Username: <input type="text" id="username"/><em id="usercheck"></em>
</form>

Upvotes: 5

Views: 5792

Answers (7)

lintal
lintal

Reputation: 349

Change your function to:

function userCheck() {
    if(document.getElementById("username").value.length > 5) {
      //no error
    } else {
      //error
    }
}

Or in jQuery:

$(function() {
   $("#username").change(function() {
      if($("#username").val().length > 5) ... 
   });
});

Upvotes: 0

Rafael
Rafael

Reputation: 569

Regarding the use of onkeypress, it is better to use onchange. For example, if the user is pasting text into the box using the mouse, onkeypress will not register this, but onchange will.

Upvotes: 0

user30920
user30920

Reputation:

use javascript to handle a DOM event for that input. see here for a list.

Maybe use onkeypress like this:
< input type="text" onkeypress="alert('you pressed a key');" / >

Use a variable if you want to track its old value and compare. Here is an example using onkeypress.

Upvotes: 1

staticbeast
staticbeast

Reputation: 2111

In javascript, you can apply an onchange event to the input to detect what the user has enterred after they have finished typing it, or an onkeypress event to listen as the user enters the data.

Then you can call your validation routine and amend the message by the input as necessary.

Upvotes: 0

Rafael
Rafael

Reputation: 569

You need to use the onchange event on the input element. Then you do an Ajax request with each call and check on the server whether the username is acceptable.

document.getElementById('username_input').onchange = checkIfTaken;
function checkIfTaken() {
  ajax_check_username(this.value);
}

Something like that. You would then obviously have to check the ajax response and show a message like "username OK" or "username is not cool".

Upvotes: 4

pkaeding
pkaeding

Reputation: 37633

What you are looking for is the onChange event. For example, if you were using prototype.js, the following would do the trick:

$('usernameFieldId').observe('change', usernameValidaitonFunction);

Upvotes: 4

John
John

Reputation: 16007

Why not do the check when the user submits the username?

Upvotes: 0

Related Questions