1

I have a js function that sets the value of id_2 based on the value of id_1. It looks like this below:

function set_value(id_1, id_2, url){
    var id_1_value;
    id_1_value = $(id_1).val();
    var value;
    ...
    /* calculation etc. */
    document.getElementById(id_2).value = value;
};

The function is linked to the id_1 html element by an onchange method like this onchange='set_value(this, id_2)'.

If I change the value in id_1 the function doesn't work and I get the following error in the console:

Unable to set property 'value' of undefined or null reference

but if I hardcode document.getElementById('id_2') in the function it works fine. How do I write this function so I can pass an element id variable to it successfully? I want to reuse this function for different elements you see...

1
  • Sorry that was an error, just changed it Commented May 4, 2016 at 10:00

4 Answers 4

1

Your set_value function should be as below.

function set_value(id_1, id_2, url) {
    var id_1_value = $(id_1).val();
    /* calculation etc. */
    if ($(id_2).length !== 0)
    {
        $(id_2).val(id_1_value);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I'm going for this one because I want to avoid having to add quotes to my input variable. The onchange=set_value(this, id_2) part is autogenerated using my django code
0

Are you passing "#id_2" to the set_value parameter?

if so that means it would return null.

// The function should be called like this 
 var id_2 =  "id_2";
 set_value(this, id_2, blah...)

Comments

0

Change the call like this

onchange='set_value(this, "id_2")'

Second parameter should be passed as string.

Comments

0

try this following code:

function set_value(id_1, id_2, url){
    var id_1_value = $(id_1).val();
    var value;
    ...
    /* calculation etc. */
    document.getElementById(id_2).value = value;
};

and onchange function

onchange="set_value(this, 'id_2')"

Comments

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.