Javascript String Return

I am trying to create a simple function that will return the correct string when called:

function getState(abbr){ if (abbr=="WY") { return "Wyoming"; } } 

and then the call is as follows:

 var stateName = getState("WY"); 

However, all that is returned: 0

Sorry if I am missing something obvious.

UPDATE - my question was because of the &, here is the real code that I mean:

 function getState(abbr){ var url = "states.asp" var state = ""; $.get(url, function(data) { var i = 0; $.each($('state',data),function(index, el) { if (abbr == ($(this).attr("abbr"))){ //alert($(this).attr("abbr")); state = $(this).text(); }//if (abbr == $(this).attr("abbr")){ });//$.each($('state',data),function(index, el) { }).success(function() { alert("x" + state); return state; }); //.success(function() { //$.get(url, function(data) { alert("y" + state); return state; } 

I get "undefined" as a result of my call:

 alert(getState("WY")); 

Alert (status "x" +) is working.

UPDATE # 2 --- thatโ€™s all that state.asp generates (at the moment) ... later it will return the company, etc .:

 <?xml version="1.0" encoding="utf-8"?> <STATELIST> <STATE abbr="AL">Alabama</STATE> <STATE abbr="AK">Alaska</STATE> <STATE abbr="AZ">Arizona</STATE> <STATE abbr="AR">Arkansas</STATE> <STATE abbr="CA">California</STATE> <STATE abbr="CO">Colorado</STATE> <STATE abbr="CT">Connecticut</STATE> <STATE abbr="DE">Delaware</STATE> <STATE abbr="FL">Florida</STATE> <STATE abbr="GA">Georgia</STATE> <STATE abbr="HI">Hawaii</STATE> <STATE abbr="ID">Idaho</STATE> <STATE abbr="IL">Illinois</STATE> <STATE abbr="IN">Indiana</STATE> <STATE abbr="IA">Iowa</STATE> <STATE abbr="KS">Kansas</STATE> <STATE abbr="KY">Kentucky</STATE> <STATE abbr="LA">Louisiana</STATE> <STATE abbr="ME">Maine</STATE> <STATE abbr="MD">Maryland</STATE> <STATE abbr="MA">Massachusetts</STATE> <STATE abbr="MI">Michigan</STATE> <STATE abbr="MN">Minnesota</STATE> <STATE abbr="MS">Mississippi</STATE> <STATE abbr="MO">Missouri</STATE> <STATE abbr="MT">Montana</STATE> <STATE abbr="NE">Nebraska</STATE> <STATE abbr="NV">Nevada</STATE> <STATE abbr="NH">New Hampshire</STATE> <STATE abbr="NJ">New Jersey</STATE> <STATE abbr="NM">New Mexico</STATE> <STATE abbr="NY">New York</STATE> <STATE abbr="NC">North Carolina</STATE> <STATE abbr="ND">North Dakota</STATE> <STATE abbr="OH">Ohio</STATE> <STATE abbr="OK">Oklahoma</STATE> <STATE abbr="OR">Oregon</STATE> <STATE abbr="PA">Pennsylvania</STATE> <STATE abbr="RI">Rhode Island</STATE> <STATE abbr="SC">South Carolina</STATE> <STATE abbr="SD">South Dakota</STATE> <STATE abbr="TN">Tennessee</STATE> <STATE abbr="TX">Texas</STATE> <STATE abbr="UT">Utah</STATE> <STATE abbr="VT">Vermont</STATE> <STATE abbr="VA">Virginia</STATE> <STATE abbr="WA">Washington</STATE> <STATE abbr="WV">West Virginia</STATE> <STATE abbr="WI">Wisconsin</STATE> <STATE abbr="WY">Wyoming</STATE> </STATELIST> 
+6
source share
5 answers

The easiest approach is to make a hash - no function is required.

 var states = { 'AL': 'Alabama', 'AK': 'Alaska', 'AZ': 'Arizona', 'AR': 'Arkansas', 'CA': 'California', 'CO': 'Colorado', 'CT': 'Connecticut', ... 'WY': 'Wyoming' }; var stateName = states["WY"]; 

EDIT

Now I better understand that getState() needs to get state names from the server. This puts you in the world of asynchronous coding, which is very different from regular synchronous coding.

The most important thing to understand is that getState() cannot just return the state name for this abbreviation. What for? Since the ajax call on the server is asynchronous - in other words, getState() will not wait for the server to respond before returning.

There are two approaches to handling asynchrony:

  • pass the callback function (s) to getState() to tell what to do when the response is received
  • arrange getState() to return a special type of object called a "promise" that can be processed where getState() is called so that it will respond when the server responds.

The code below uses the second approach.

 var states = {};//cache of state names, with state abbreviations as keys function getState(abbr) { var dfrd = $.Deferred();//A deferred object, whose promise will be returned. if(!states[abbr]) { $.ajax({ url: "states.asp", dataType: 'XML', success: function(data) { //Load up the cache $.each($('state', data), function(i, el) { states[el.attr('abbr')] = $(el).text(); }); //Now resolve or reject the deferred object depending in whether states[abbr] has been cached if(states[abbr]) { dfrd.resolve(abbr, states[abbr]);//Success! Let resolve the deferred object (and its promise). } else { dfrd.reject(abbr, 'States successfully downloaded but ' + abbr + ' was not included'); } }, error: function() { dfrd.reject(abbr, 'Download of states failed'); } }); } else { //The state name is already cached //The deferred object (and its promise) can be resolved without needing to make another ajax call. dfrd.resolve(abbr, states[abbr]); } return dfrd.promise(); } 

untested

Now all you have to do is call getState() .

 getState("WY").done(function(abbr, state) { alert(abbr + ': ' + state); //other stuff here }).fail(function(abbr, message) { alert(abbr + ': ' + message); //other stuff here }); 

As you can see, the value you wanted getState() to return now appears as the second argument to the .done() function. For good measure, the abbreviation ("WY") appears as the first argument.

If you want to handle error conditions (always a good idea) then do it in the .fail() .

See the comments in the code for more details on how everything works.

+7
source

Nothing is broken in your code. See This Working Demo .

 function getState(abbr){ if (abbr=="WY") { return "Wyoming"; } } var stateName = getState("WY"); alert(stateName);โ€‹ 
+3
source

HTML:

 <div id="msg">...</div> 

JS:

 function getState(abbr){ if (abbr=="WY") { return "Wyoming"; } } var stateName = getState("WY"); โ€‹document.getElementById('msg').innerHTML=stateName; 
+3
source

It will be many if to evaluate: functions may have to go through all 50 if statements to get to Wyoming! I would rewrite it with a switch , for example:

 function getState(abbr){ switch case(abbr) { case "WY": return "Wyoming"; ... } } 

I think it should be faster. I would also add the default case, in case the input is bad.

+2
source

This is just my decision. I still grab onto a straw trying to figure out asynchronous behavior, but here's what worked:

Instead:

 function searchServing(which,choice){ var state = getState("WY"); $("#searchResults").html("<tr><td>" + state + "</td></tr>"); .get(function() { } //for reference call this getSearchServing } 

I had to cancel the call like this:

 function getState(abbr){ .get(function(){ $("#searchResults").html("<tr><td>" + state + "</td></tr>"); }) .success(function() { searchServing('serving',abbr); }) } 

still not sure why getSearchServing will work before getState and not sure why I couldnโ€™t return the value from getState ???

0
source

All Articles