Jump to content

Recommended Posts

I need to create a javascript function which will only do something once. For example, there is a text box with preset text in it. Onfocus wipes that content so that the user can type their own in. However, I need it to only wipe the content once so I need that onfocus to be disabled after the first time. Is there a way of doing this all in javascript?

 

Is there a way of changing the javascript function using javascript? So that onfocus I could have something at the end of the function which then changes the onfocus event to something else.

 

Cheers

Joe

Link to comment
https://forums.phpfreaks.com/topic/243090-javascript-do-something-only-once/
Share on other sites

You can easily make a JavaScript function overwrite itself:

 

var foo = function() {
  alert('say foo');
  foo = function() {
    alert('never again say foo');
  }
}
foo();
foo();
foo();

 

The first time you call foo() it will display 'say foo', every other call after that will display 'never again say foo'.

If you remove the function or only allow it to work one time, you would need to create a function for each input field (which defeats the purpose of a function). You can do something like this instead (notice the title is the same as the default value)

<input type="text" value="Default Value" title="Default Value" onfocus="if (this.value == this.title) this.value = '';" onblur="if (this.value == '') this.value = this.title;" />

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.