0

I just wondering why I get the error when I do the following:

function something(id){
    return document.getElementById(id).value;
}
something('id') = 'hello';

But I can do this without error:

document.getElementById('id').value = 'hello';

They are suppose just the same thing, right?

Of course, assume there is an input element with id, named 'id'.

Thanks.

  • possible duplicate of [What's a valid left-hand-side expression in JavaScript grammar?](http://stackoverflow.com/questions/3709866/whats-a-valid-left-hand-side-expression-in-javascript-grammar) – Bergi Feb 03 '14 at 08:10

2 Answers2

0

Well in the first example you try to assign something to the result of a function, while in the second example you assign something to a property of an object.

Maybe the misunderstanding results from the fact that the return value of the function is just the "contents" of the property (i.e. a string) and not a reference to it.

To achieve what you are trying to do, you need to call the function with the value and do the assigning there:

function something(id, v){
    document.getElementById(id).value = v;
}
something('id', 'hello');
akirk
  • 6,757
  • 2
  • 34
  • 57
0
  1. You're first approach is about retrieval data.

  2. Whereas the second part is about assigning the data. Here You're are assigning value to something function variable.

May you need to change like below

function something(id, val){
    document.getElementById(id).value = val;
    return document.getElementById(id).value;
}

Then call it like

something('id', 'hello');
Praveen
  • 55,303
  • 33
  • 133
  • 164