0

I have this small code. I am using the Prototype framework but I am unable to bind elements to the callback function. That's why I have to write the function like this.

How may I improve this code?

 Event.observe('firstname', 'keyup', function () {
     var form = $('customerform'),
         firstname_0 = form["firstname_0"];
     firstname.value = this.value;
 });
 Event.observe('KundeNachname', 'keyup', function () {
     var form = $('customerform'),
         lastname_0 = form["lastname_0"];
     lastname_0.value = this.value;
 });

2 Answers 2

1

The only difference between each of your callbacks is the name of the form field that's referenced. I'd extract that code into a common callback-creating function:

function createHandler(fieldName) {
    return function() {
        $('customerform')[fieldName].value = this.value;
    }
}

Event.observe('firstname', 'keyup', createHandler("firstname_0"));
Event.observe('KundeNachname', 'keyup', createHandler("lastname_0"));
Sign up to request clarification or add additional context in comments.

Comments

1
$('customerform')['lastname_0'].value = this.value;

This condenses your three lines of code into one.

1 Comment

Shouldn't it be $('customerform')['lastname_0'].value = this.value;?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.