Change an element's onfocus handler with Javascript?

半世苍凉 提交于 2020-01-14 12:03:24

问题


I have a form that has default values describing what should go into the field (replacing a label). When the user focuses a field this function is called:

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

The onfocus is set to null so that if the user puts something in the field and decides to change it, their input is not erased (so it is only erased once). Now, if the user moves on to the next field without entering any data, then the default value is restored with 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);
    }
}

It just so happened that the default values were the names of the elements so instead of adding an ID, I just manipulated the name property. The problem is that if they do skip over the element then the onfocus event is nullified with clear_input but then never restored.

I added

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

In restore_default function but that doesn't work. How do I do this?


回答1:


Use

element.onfocus = clear_input;

or (with parameters)

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

with

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

The "javascript:" bit is unnecessary.




回答2:


It looks like you don't allow the fields to be empty, but what if the user puts a single or more spaces in the field? If you want to prevent this, you need to trim it. (See Steven Levithans blog for different ways to trim).

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

If you really want to capitalize the strings you could use:

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

By clearing the onfocus event you have created a problem that should not have been there. An easier solution is to just add an if-statement to the onfocus event, so it only clears if it is your default value (but I prefer to select it like tvanfosson suggested).

I assume that you on your input-elements have set the value-property so that a value is shown in the input-elements when the page is displayed even if javascript is disabled. That value is available as element.defaultValue. Bonuses by using this approach:

  • You only define the default value in one place.
  • You no longer need to capitalize any value in your handlers.
  • The default value can have any case (like "John Y McMain")
  • The default value no longer needs to be the same as the name of the element.

.

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;}
}



回答3:


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

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);
    }
}



回答4:


<!-- 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>


来源:https://stackoverflow.com/questions/292861/change-an-elements-onfocus-handler-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!