Welcome to WebmasterWorld Guest from 54.147.44.13

Forum Moderators: open

Message Too Old, No Replies

Invalid left-hand side in assignment error using function

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

Full Member

5+ Year Member Top Contributors Of The Month

joined:Sept 30, 2009
posts:222
votes: 0


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?
12:35 pm on July 21, 2014 (gmt 0)

Senior Member from US 

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

joined:Oct 17, 2005
posts: 4965
votes: 10


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