homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

Invalid left-hand side in assignment error using function

5+ Year Member

Msg#: 4689336 posted 3:05 am on Jul 21, 2014 (gmt 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;
$("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?



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

Msg#: 4689336 posted 12:35 pm on Jul 21, 2014 (gmt 0)

Your function, v, will pass by value the string value in property "value". So when you do this:
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

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved