Welcome to WebmasterWorld Guest from 54.160.131.144

Forum Moderators: open

Message Too Old, No Replies

Invalid left-hand side in assignment error using function

     

ocon

3:05 am on Jul 21, 2014 (gmt 0)

5+ Year Member Top Contributors Of The Month



I'm defining the following variable at the begining of my JavaScript to allow me to shorten my scripts without having to use any bulky libraries like jQuery:

var $=function(n){return document.getElementById(n)};

It's great, I can shorten my code like this:

document.getElementById("a1").style.display = "none";
document.getElementById("a2").value = 5;
var temp = document.getElementById("a3").value;
to
$("a1").style.display = "none";
$("a2").value = 5;
var temp = $("a3").value;

I grab and set a lot of values with my scripts, so I wanted to add a new global variable:

var $=function(n){return document.getElementById(n)}, v=function(n){return $(n).value};

My plan was to allow me use code like:

$("a1").style.display = "none";
v("a2") = 5;
var temp = v("a3");

Unfortunately, I'm getting a "Invalid left-hand side in assignment" error.

I tried modifying my code without luck to:

var $=function(n){return document.getElementById(n)}, v=function(n){return document.getElementById(n).value};

Is there any way I can modify my code to make this work?

Fotiman

12:35 pm on Jul 21, 2014 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Your function, v, will pass by value the string value in property "value". So when you do this:
v("a2")
You are getting a string copy of the value, and therefore when you attempt to do the assignment, you get the invalid left hand side in assignment.

Instead, try something like:
v=function(n,val){if(typeof val!=='undefined'){$(n).value=val}else{return $(n).value}};

And then:
v("a2") // Get value
v("a2", 5) // Set value