Change onfocus handler element with javascript?

I have a form that has default values ​​that describe what should go in the field (replacing the label). When the user focuses the field called by this function:

function clear_input(element)
{
    element.value = "";
    element.onfocus = null;
}

Onfocus is set to null, so if the user puts something in the field and decides to change it, their input is not deleted (therefore, it is only erased once). Now, if the user moves to the next field without entering any data, the default value is restored using this function (called onblur):

function restore_default(element)
{
    if(element.value == '')
    {
        element.value = element.name.substring(0, 1).toUpperCase()
                          + element.name.substring(1, element.name.length);
    }
}

, , name. , , onfocus clear_input, .

element.onfocus = "javascript:clear_input(this);";

restore_default, . ?

+3
4

element.onfocus = clear_input;

( )

element.onfocus = function () { 
    clear_input( param, param2 ); 
};

function clear_input () {
    this.value = "";
    this.onfocus = null;
}

"javascript:" .

+7

, , , ? , . ( ).

function trim(str) {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

, :

function capitalize(str) {
    return str.substr(0, 1).toUpperCase() + str.substr(1).toLowerCase();
}

onfocus, , . if-statement onfocus, , ( , tvanfosson).

, value , , , javascript . element.defaultValue. , :

  • .
  • - .
  • (, "John Y McMain" )
  • .

.

function clear_default(element) {
    if (trim(element.value) == element.defaultValue ) { element.value = ""; }
}

function restore_default(element) {
    if (!trim(element.value).length) { element.value = element.defaultValue;}
}
+1

I would suggest that you handle this a little differently. Instead of clearing the value, why not just highlight it all so that the user can simply start typing to overwrite it. Then you do not need to restore the default value (although you can still do it the same way if the value is empty). You can also leave the handler in place, since the text is not cleared, it is simply highlighted. Use validation to ensure that the value is not the original input value.

function hightlight_input(element) {
    element.select();
}

function restore_default(element) // optional, do we restore if the user deletes?
{
    if(element.value == '')
    {
        element.value = element.name.substring(0, 1).toUpperCase()
                          + element.name.substring(1, element.name.length);
    }
}
0
source
<!-- JavaScript
function checkClear(A,B){if(arguments[2]){A=arguments[1];B=arguments[2]} if(A.value==B){A.value=""} else if(A.value==""){A.value="Search"}}
//-->

<form method="post" action="search.php">
<input type="submit" name="1">
<input type="text" name="srh" Value="Search" onfocus="checkClear(this,'Search')" onblur="checkClear(this,' ')">
</form>
0
source

Source: https://habr.com/ru/post/1699614/


All Articles