JavaScript – Playing with a Form

JS - JavaScriptI assume you already saw one of those forms which show something like „Enter query“ in one of the input fields and as soon as you enter a letter or press a key on the keyboard, the „Enter query“ vanishes.

As I needed such a feature for a project of mine, I decided to write this tutorial to share a couple of techniques you can use for such an interesting form.

Form #1

The first form has the mentioned feature that removes the text in the input field as soon as you hit a key:
<script type="text/javascript">
<!--
function clear_input($input)
{
if (document.getElementById($input).value == "Name" || document.getElementById($input).value == "Password")
{
document.getElementById($input).value = '';
};
}
window.onload = document.getElementById("name-1").value="Name";
window.onload = document.getElementById("password-1").value="Password";
//-->
</script>

Put this code at the bottom of the page, replace the getElementByID values and IDs with the ones you are using, then add the event onkeypress="" to the input box you want to have using this feature. Inside the onkeypress="" you add clear_input('id of the input field');return true;.
For my example it would be for the „name“ input field: onkeypress=" clear_input('name-1'); return true;"

The „return true“ is a bug fix for some browsers which won’t clear the input field as we want it.

Form #2

This form will check the input data before it submits it:
<script type="text/javascript">
<!--
function check_input()
{
if (document.getElementById("name-2").value != "Name" && document.getElementById("name-2").value != "" && document.getElementById("password-2").value != "Password" && document.getElementById("password-2").value != "")
{
return true;
}
else
{
return false;
}
}
function clear_input($input)
{
if (document.getElementById($input).value == "Name" || document.getElementById($input).value == "Password")
{
document.getElementById($input).value = '';
};
}
window.onload = document.getElementById("name-2").value="Name";
window.onload = document.getElementById("password-2").value="Password";
//-->
</script>

As you see I’m using the clear_input() function again and added a check_input function. Add onsubmit="return check_input;" to the opening form tag and make sure you are using the right IDs in your script.

If everything is working, your form should behave like mine.

Wrap Up

I hope this tutorial gave you an idea or two on how to improve your form a little bit. An idea which just pops up right now is to combine the clear_input method with Ajax to provide search suggestions, if it is a search form. Or you add a check_mail variant which validate an inserted email on the fly.

There are many options. Do you know a special one and have no idea how to achieve it? Or do you want to share an idea or script? I’m happy about any kind comment!

Schreibe einen Kommentar