Alex
Alex

Reputation: 61

changing the value of a form field with a custom method?

I created a method called removeValue to remove the value of formfields. Every time the user clicks on it, I put in the onclick event with the function to be executed, in the html, it gives this error: "cannot reference to variable of ..." (something like that). Why is that?

I thought the keyword this always refers to the object being called, if I write this.value =""; directly in the HTML, it works. Why is that?

function removeValue () {  
    if (this.value != "") {
        this.value = ""; 
    }
}

Upvotes: 0

Views: 34

Answers (1)

Wulf
Wulf

Reputation: 3898

this refers to the window object in this case. Pass your element to the function like this:

function removeValue(element) {
    element.value = '';
}

<input onclick="removeValue(this)" type="text">

I think it would be better if you bind the function to the onfocus event, because then it gets also called when switching to the input field with tab.

Upvotes: 2

Related Questions