jQuery – Check All Checkboxes Toggle Method Thingy

So here’s a quick on for all you boys and girls… and anything else I might have missed.
Say you want to check all check boxes in a grid or whatever, but you want it to toggle. So if if it’s time to check all, all get checked and then the next time the button is clicked it will uncheck. Now you could do this in three methods, maybe two but that’s why you’re a mouth breather.

Special people like me do it in one.

    function toggleCheckboxes(buttonId, checkBoxNamePrefix, checked)
    {
      //Get all checkboxes with the prefix name and check/uncheck
      jQuery('[id*=' + checkBoxNamePrefix + ']').attr('checked', checked);

      //remove any click handlers from the button
      //  Why?  Because jQuery(buttonId).click() will just add another handler
      jQuery(buttonId).unbind('click'); 

      //Add the new click handler
      jQuery(buttonId).click(
        function() {
          toggleCheckboxes(buttonId, checkBoxNamePrefix, !checked);
        }
      );
    }

And POW! What? You want to know how to use it? Fine, but only because I’m nice.

   jQuery('#buttonName').click(
     function() {
       toggleCheckboxes('#buttonName', 'someCheckBoxName', true);
     }
   );

And in case you were still wondering why I used .unbind and didn’t understand the comment, it’s because using just .click will add another handler to the button. So next click you will get both check and uncheck all. Kind of hurts the effectiveness.

And there you have it. Once again I have filled your life with meaning. Couldn’t be easier. Or maybe it could but that’s not my problem now is it? Go back to doing something useful.

jQuery Validation: Adding Errors to the Error Containter… With Love!

Hello again, my wonderful audience, I have something great and fun planned for this post. If you read this post you might have been left wondering how to add custom messages to the error holder. It’s ok if you did, there’s nothing wrong with being confused all the time. It’s what makes you so adorable.

Say you have a form like this, and if you don’t I cry endlessly for your loss. My heart goes out to you.

<form id="ILoveEverythingForm">
    <div id="NotSoNiceThingsDiv" style="display:none;"></div>
	...
</form>

As you can see, there is an error div to hold mean things that we have to print out because the system just doesn’t like the user. As we both know, the user can’t help but be dumb. It’s just in his cute little nature. And that nature is just so darned cute.

Now let’s assume that you have something that sent back a bunch of mean messages when you tried to validate server side after all the cute client side validation was done. You might have a method to take in those jerk face messages. How do you display them in the bad place?

  function updateErrorDivContentWithLove(messages)
  {
    if(messages.length > 0)
    {
      var validator = jQuery('#ILoveEverythingForm').validate();

      for(var loopCounter = 0; loopCounter < messages.length; loopCounter ++)
      {
        validator.showErrors
        (
          {
             'SomeWonderfulElementName' : messages[loopCounter].Message
          }
        );
      }
    }
  }

Awwww kitties!

  

Only thing that may seem odd (And if it doesn’t, don’t worry you are still very special and loved in this world):

  'SomeElementName' : messages[loopCounter].Message

Not sure what element really needs to be here, basically anything in the form with a name tag. So if you’re good like I know you are, you have at least one element in that little old form with a name property set. I would say that this is pretty useless in situations where all the errors are shown in one div, as opposed to right next to the element, but that would be mean and I don’t do that.

Now I know you wanted something special from this post so I just wanted you to know that even though most of the world considers you hideous, I say you should be proud of being hideous because it makes you who you are. A unique miracle that only really has issues with dogs and small children. Embrace yourself in whatever way you take that!

Custom Data Annotations With MVC: How to Check Multiple Properties at One Time

Ok so maybe you read this post and you’re thinking to yourself, “I wonder if Diet Dr. Pepper really does taste like regular Dr. Pepper” which of course is silly because the ads clearly say it does. Now you should be asking yourself, “How do I check if two properties have the same value on a class with annotation when the property level ones only can check the one property’s value?” Kind of wordy way of asking that, but I get what you’re asking. Better yet, like usual, I have an answer.

Now what I can swear is that I was no where near the Baxter Building between 1-3 am on Saturday the 15th. I was in fact I was sleeping and have 20 witnesses that can testify. What I can’t swear is this is the best way to go about it but it seems to work AND make sense. It’s not common for me to come up with solutions that do both.

  [AttributeUsage(AttributeTargets.Class)]
  public class PropertiesMatchAttribute : ValidationAttribute
  { 

    public String FirstPropertyName { get; set; }
    public String SecondPropertyName { get; set; } 

    //Constructor to take in the property names that are supposed to be checked
    public PropertiesMatchAttribute(String firstPropertyName, String secondPropertyName )
    {
      FirstPropertyName = firstPropertyName;
      SecondPropertyName = secondPropertyName ;
    } 

    public override Boolean IsValid(Object value)
    {
      Type objectType = value.GetType();
      //Get the property info for the object passed in.  This is the class the attribute is
      //  attached to
      //I would suggest caching this part... at least the PropertyInfo[]
      PropertyInfo[] neededProperties =
        objectType.GetProperties()
        .Where(propertyInfo => propertyInfo.Name == FirstPropertyName || propertyInfo.Name == SecondPropertyName)
        .ToArray();

      if(neededProperties.Count() != 2)
      {
        throw new ApplicationException("PropertiesMatchAttribute error on " + objectType.Name);
      }

      Boolean isValid = true;

      //Convert both values to string and compare...  Probably could be done better than this
      //  but let's not get bogged down with how dumb I am.  We should be concerned about
      //  dumb you are, jerkface.
      if(!Convert.ToString(neededProperties[0].GetValue(value, null)).Equals(Convert.ToString(neededProperties[1].GetValue(value, null))))
      {
        isValid = false;
      }

      return isValid;
    }
  }
}

And then the use:

  [PropertiesMatchAttribute("Password", "ConfirmPassword", ErrorMessage = "Match the passwords, dumb--s.")]
  public class UserCreateModel
  {
     public String ConfirmPassword{ get; set; }
     public String Password { get; set; }
  }

Wasn’t so hard was it? Normally this would be the part where I degrade you for being bumb because you didn’t figure this out but I’m above that now. I guess it must be the holiday season or that I’ve been told by the board that I should be more gentle with my readers. Guess some were crying after reading some of my posts. Yeah whatever. Bunch of [Removed by Andre].

Data Annotations, MVC, and Why You Might Like Them

So if you were like me before I knew what Data Annotations were, you most likely would be thinking, “What are Data Annotations?”. Well I’m glad I can read your mind and therefore I am glad you asked.

Now the fun part about this post is that I might have to admit I was wrong. Why would that be? Well in this post I suggested that validation rules would be set in the controller. Turns out, there is possibly a better place, on the model itself. How can this be done??? Well that’s what you’re about to find out.

Say you have a user create model:

  public class AddUserModel
  {
    public String UserName { get; set; }
    public String Password { get; set; }
    public String RepeatPassword { get; set; }
  }

Now you could have a method on the controller like:

  public ActionResult AddUser(AddUserModel model)
  {
    if(IsValid(model))
    {
      ...
    }
  }

Where you have to create the IsValid method for every model on the controller that you need to validate (And possibly on other controllers if you are sharing models between them…) Or you can have this:

  public ActionResult AddUser(AddUserModel model)
  {
    if(ModelState.IsValid)
    {
      ...
    }
  }

And that is already built in so no validation method needed. But how is that possible? Attributes on the model or namely the ValidationAttribute class.

First off you have to include the System.ComponentModel dll in the project. Simple enough. Please say you know how to do that or do me a favor and remind yourself to blink. OK done? Good.

Now you can use some of the built in attributes which is good. Things like required are nice:

  public class AddUserModel
  {
    [Required]
    public String UserName { get; set; }
    ...
  }

There you go. Now if the UserName is null or empty, the ModelState will no longer be valid and will fail this check:

  ModelState.IsValid

Now you might wonder what the error message will be for that? Honest answer: I have no f–king clue. That’s why you can actually set it. Those guys at Microsoft thought of everything.

  public class AddUserModel
  {
    [Required(ErrorMessage = "ENTER A USERNAME IDIOT!"]
    public String UserName { get; set; }
    ...
  }

The guys in the legal department have told me I have to note that your error message should change depending on your use and you shouldn’t use the one above. Whatever.

Now you might want to actually pass the errors back, and why wouldn’t you? You’re a fine, upstanding, and thoughtful person and I lie like a crook. The errors, if there are any, are in here:

  ViewData.ModelState.Values

And you can use two loops to get to all of them, but I think the parent loop will only run once.

  foreach (ModelState state in ViewData.ModelState.Values)
  {
    foreach (ModelError error in state.Errors)
    {
      messageList.Add(error.ErrorMessage);
    }
  }

Pretty nice huh? Maybe if you’re an idiot who just learned about this. For cool people like me, it’s old news.

What’s the point this? If “this” is data annotations: Well it helps move some of the validation off the controller if you are looking for a more “Fat model, skinny controller” design which I’m told is a good idea. This also gets rid of all the validation methods and saves time because of it.

If “this” is your life? I have no idea. But if you’re to the point that you’re asking me about the meaning of your life, you are in some serious trouble.

jQuery Grab Bag – Whole bunch of jQuery Functionality

You could look at this post as a self serving block that I will use to save stuff I don’t want to remember later.

Or you could see it as a knowledge transfer that you the reader can learn from because I am a generous and giving tool.

Whatever, I really don’t care. I won’t sleep any differently. I just don’t feel like making 1000 posts of jquery stupidity.

I’ll add more as I come across them.

Checkbox

How To Check a CheckBox

  jQuery('#CheckBoxId').attr('checked', false);

How To Know if a Checkbox is Checked

  jQuery('#CheckBoxId').is(':checked')

How To Find a Bunch of Like Named Checkboxes that are Checked

  jQuery('[id*=someCheckBox_]:checked');

Drop Down Lists

How to Add an Item/Option to a Drop Down List

 jQuery('#DropDownListId').append(jQuery('<option>').val(1).html("SomeText"));

Odd Note: Apparently jquery is smart enough to set the attributes on the option AND close the option with </option>

How to Remove an Item/Option from a Drop Down List

  jQuery('#DropDownListId option[value=\'3\']').remove();

How to Sort a Drop Down List by Option Text

  var sortedList = jQuery('#someDropDownList option').sort(
    function (first, second) {
      return first.text == second.text ? 0 : first.text < second.text ? -1 : 1;
    }
  );

  jQuery('#someDropDownList').html(sortedList);

Elements

How to Filter Out an Element in a List

  someElementList.filter('[id=someId]');

Example:

  //Uncheck all id like someId_ and check only where id = someId_1
  var someElementList = someElement.children('[id*=someId_]');
  someElementList.attr('checked', false);
  someElementList.filter('[id=someId_1]').attr('checked', true);

How To Find an Element Based on a Like Name/Using Wildcards

  jQuery('#SomeTable').children('tr[id*=SomeRowId]');

How To Know if a Something is Hidden

  jQuery('#CheckBoxId').is(':hidden')

Possible Use:

 function showOrHide(element) {
    if(jQuery(element).is(':hidden')) {
      jQuery(element).show();
    }
    else {
      jQuery(element).hide();
    }
  }

How to Disable an Input/Select

  jQuery('#DropDownListId').attr('disabled', 'disabled');

How to Enable an Input/Select

  jQuery('#DropDownListId').removeAttr('disabled');

How to Know if an Element Exists

  jQuery('#ElementId').length > 0

Possible use:

  function elementExists(elementId) {
    return jQuery(elementId).length > 0;
  }

String

How To Remove the First Character from a String

  someString.substring(1, someString.length)

Tables

How to Add a Row to a Table

  jQuery('#TableId > tbody:last').append('<tr>...</tr>')

How to Remove a Table Row

  jQuery('#TableId > tbody:last').children(someSortOfRowId).remove();

Methods

How to Post With a Link

  function postToUrl(path, params)
  {
    var method = "post"; 

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);
    for(var key in params)
    {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);
        form.appendChild(hiddenField);
    }
    document.body.appendChild(form);    

    form.submit();
  }

Use:

<a href="javascript:postToUrl('/SomeController/SomeAction/', { 'id', '1' })">link</a>

jQuery Validation – How to Use to Get Rid Of Even The Toughest Stains

So you want to use jQuery validation, huh?

What is it? Something that was added to the holy jquery site and is an easy way to validate input from users. Now this should in no way take over for server side validation, but it helps to at least catch a few things without having to send anything to the server. So how do ya do it?

Well to start, you need some files:

jquery-1.3.2.js and jquery.validate.js.

Now oddly enough the validation file isn’t hosted on the holy jquery site but how to use it is.

Ok now you have the files, what’s next? Well you need form, and I can do that for you.

So basically it’s a simple form with one input that is required.

jQuery(document).ready
    (
      function()
      {
        jQuery("#PrimaryForm").validate
        (
          {
            errorLabelContainer: "#ErrorDiv",
            wrapper: "div",
            rules:
            {
              FirstName :
              {
                required : true
              }
            },
            messages:
            {
              FirstName:
              {
                required : 'First Name is required.'
              }
            },
            onfocusout : false,
            onkeyup: false,
            submitHandler: function(label)
            {
              postSubmit();
            }
          }
        );
      }
jQuery("#PrimaryForm").validate

Real simple, just setting the validator to the primary form on the page.

 errorLabelContainer: "#ErrorDiv",

This sets the errors to show up in the ErrorDiv. Now this is optional, as you can have it show the errors next to the FirstName text box but personally I think that looks horrible. Setting up the ErrorDiv puts all the errors in one central location and allows for styling the actual div.

 rules:
 {
    FirstName :
    {
      required : true
    }
  },

This matches an element with the id of FirstName to the required rule, meaning that FirstName is required. Rocket science.

  messages:
  {
    FirstName:
    {
       required : 'First Name is required.'
    }
  },

If you can’t figure this out, I hear circus is hiring for the “World’s Dumbest Person”. You’ll fit in with Jub Jub the Dog Boy.

  onfocusout : false,
  onkeyup: false,

Basically this prevents the validation when leaving the textbox or on every key press. This is just another preference.

  submitHandler: function(label)
  {
    postSubmit();
  }

If the submit is successful, call this method.

But… BUT WHAT IF IT’S AN EMAIL?!??! WHAT WILL I DO???!?!?

Well for one, stop being such a child. And two, look here.

Some what different, as you can see it’s now email and there is one extra requirement in the rules:

  rules:
  {
    EmailAddress :
    {
      email : true,
      required : true
    }
  },
  messages:
  {
    EmailAddress:
    {
      required : 'Yo, email fool.',
      email : 'So not an email address.'
    },
  },

See? It has nice built in rule for email. Simple.

BUT WHAT IF I NEED A REGULAR EXPRESSION?!??! WHAT WILL I DO???!?!?

I swear if you don’t stop that, I’m turning this post around and going home.

Fine here it is.

  jQuery.validator.addMethod
  (
    "isZipCode",
    function(value, element)
    {
      return value.match(new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/));
    }
  );

Just have to create a method and “add it” to the validator itself. And then there’s the use:

  rules:
  {
    ZipCode :
    {
      required : true,
      isZipCode : true
    }
  },
  messages:
  {
    ZipCode:
    {
      required : 'For the love of me, enter a zip code!.',
      isZipCode : 'Serioulsy?  Do you know what a zip code is?'
    },
  },

Woo hoo right?

Don’t do it… Don’t you yell.

But what if one input depends on another?

Much better. Well that’s not as hard as it may seem and here’s the example.

  rules:
  {
    InputB :
    {
      required :
      {
        depends : function(element) { return jQuery('#InputA').val() != "" }
      }
    }
  },

As you can see, you can change how the required method works by adding in a depends handler. Works out pretty well.

Yes I will show you how to make sure two inputs match. I swear you ask for a lot.

  rules:
  {
    Password :
    {
      equalTo : "#ConfirmPassword"
    },
  },

Couldn’t be easier unless I wrote it out for you. Wait, I did.

So here you’ve either learned a bit about jQuery validation or have just spent the last few minutes drooling uncontrollably. Either way, I’m done with this post and you’re left to do whatever it is you do, you sick f—.

Side note: I haven’t actually been to Htmlgoodies since eh college? but wow did that place sell out. How fitting that an introduction to html page now looks like it was designed by someone just starting out… in the 90s.

Off Topic Sunday: Does Not Liking Quentin Tarantino Make Me A Mutant?

COMPLETELY NOT PROGRAMMING RELATED

Any time I declare this I always get the same look people had when that one dude in Total Recall took off his glove and had that weird chicken wing arm thing. I can’t think of many directors that get the same free pass as he does for making, in my crazy mutant opinion, two good movies: Pulp Fiction and that one part of Four Rooms with the Zippo lighter bet. Ok so one movie and a section of another. Maybe Kill Bill 2 could be in there. Maybe.

Now I have to admit that I’ve been accused of having less than main stream opinions on movies. I’m not one of those people that only like a movie if it’s made on a 10k dollar budget and ends up just as depressing as it started. (IE Every independent movie ever.) I enjoy movies that are thought provoking and relevant as questions like “What would green smell like?” or “Why do I have 10 ten toes?” However, I liked Star Trek: The Motion Picture the most out of the six because I felt it was very Star Trek like and the most intense of the bunch. I liked Alien 3 more than Aliens (Only after watching the Director’s cut version though) because it had more thought out undertones. I think that Kill Bill 2 is far more interesting than 1 because it had story minus a bunch of tools running around like they’re athletic (See The Matrix). I also still find Godzilla versus Mechagodzilla to be the best, even though Godzilla 2000 is far superior in ever aspect, because that one part where Gozilla and King Caesar are standing in front of and behind, respectively, Mechagodzilla and they think they have it flanked when it turns it’s head around to look at King (With it’s laser eyes) and swings out it’s missle hands at Godzilla almost as if it was sayin, “You thought you got me, but I got missles b–ch. You ain’t got s–t. ”

Three things you can take from that: I probably don’t line up with your tastes, I do have thought out excuses for my “condition”, and I am a massive geek. I honestly feel that at this point I need to boost a car, take some E, and bench press 800 pounds at the same time to offset the horrendous black hole of geek I just created that threatens to pull us all in to an alternate, more geeky version of the world. No one wants that. No one but Adam Savage wants that.

At this point, you might see where I’m coming from. I’m clinically insane. However, that doesn’t mean I’m not entitled to an opinion on Tarentino. The guy is like a 12 year old with a budget.

Remember when you were 12, watching Power Rangers, sitting in a rocking chair, while lathering yourself in a mixture of peanut butter and motor oil? Probably not (But if you do, call me) but you might remember watching a movie like Aliens and thinking “What if the aliens could talk?” or “What if the Aliens could use guns, that would be sweet cause they would be all like ‘What up!’ BLAM BLAM ‘Screw you Marines!'” And let’s be honest, there’s a reason why you weren’t making films at 12… or probably even now. (Honestly? Aliens using guns? What the hell were you on at 12?) Every time I see one of his movies now, that’s all I can see: Tarantino lathered up in pean… Wait… I see Tarantino sitting around writing some movie, probably a masterpiece about a child who is taken from his family, forced into slavery, and then finds a way to unite the slaves against the slavers and bring peace to the his people. Followed by weeks of “What if aliens some how helped him free his people?” and then “What if the aliens give him awesome laser weapons and then there’s a scene where he’s all like ‘I’m gonna make them pay’ while standing on a mound of dead slavers and then he points the gun at one that’s still sort of alive and shoots him and his head explodes and the aliens start dancing in joy! Oh man that’d be cool.” (You might also call this the “Lucas effect”) Somewhere, at some point, the good ideas he may have go from a smooth riding train to a train that just lost a wheel, jumped the track, and is plowing through some childrens’ hospital.

And guess maybe that’s the problem I have with him. It’s clear that the guy is good with conversations and characters. It’s clear that he could be a premier writer. It just seems like the 12 year old side of him takes over at some point. Oh well, that 12 year old has done him well financially so who am I to say what’s good?

In the end, it just comes down to preference. Maybe I don’t have the part of the mind that gets satisfaction from way over the top insanity in movie form (I think it’s seated somewhere in between the part that enjoys chili cheese fries and the part that makes people stop and stare at highway accidents.), and if you do well more power to you. Just don’t judge me based on my thinking he’s straight up overrated or that he isn’t a god of filming. Then again I’m not the kind of person who looks for religious overtones in the Star Wars series, so maybe I’m just too dumb to see the brilliance.

Oh and side note: HE HAD NOTHING TO DO WITH HERO EXCEPT WITH HELPING WITH PUSHING UP THE TIME LINE OF THE US RELEASE. Don’t f–king even think he had any real hand in what’s probably the best epic movie in existence.

Other Note: Apparently resident “computer wiz” Andre refused to read more than the title of this post. He’s one of them…

Random Add-On – Automapper

So if you’ve bothered reading my posts in the past, and don’t worry cause I haven’t, you might have seen me express my rule about not wanting to use third party stuff. Well things change. Actually they don’t, as I’m not bending the rule because I’m becoming a better person, just more lazy. This is where Automapper comes in.

Automapper is pretty much what it sounds like, it maps class properties automatically. Maybe a more clevererest name would have been ClassPropertyAutoMapper, but the guys who made it shouldn’t be persecuted for lacking creativity.

How simple is Automapper? Simple enough that even you can use it. Now that’s simple! Say you have two classes, a entity class and a model, and you want to map the model to the entity in the constructor. You could do:

  public class SomeModel
  {
    public SomeModel(SomeEntity someEntity)
   {
     SomeProperty = someEntity.SomeProperty;
   }
  }

But where’s the lazyiness? I expect so much less from you. But it’s ok, salvation is right here:

  public SomeModel(SomeEntity someEntity)
  {
    Mapper.CreateMap();
    Mapper.Map(someEntity, this);
  }

But… but what if there are properties on SomeModel that don’t directly map by name? Well, there’s an ap…i for that. (Not sure that even makes sense but it was clever.)

  public SomeModel(SomeEntity someEntity)
  {
    Mapper.CreateMap<FiftyPostUser, UserInfoViewModel>()
     .ForMember(test => test.Status, tester => tester.MapFrom(item => item.Status.ToString()));
    Mapper.Map(someEntity, this);
  }

So I know you’re thinking that there’s a catch, well there is. You have to actually get the dll and reference in your project. I know! Work is hard. Why can’t these guys just come to your place of work/home/mom’s basement and do it for you? What kind of world is it when you can’t get all that for free? Personally, I hate it.

State List in Dictionary Form

Tired of having to look this up from time to time, so I’m putting this here for my own use. If you get something out of it, good for you. In the end, I really don’t care.

    public Dictionary GetAllStates()
    {
      if(_stateList == null)
      {
        _stateList = new Dictionary();

        _stateList.Add("Alabama","AL");
        _stateList.Add("Alaska","AK");
        _stateList.Add("American Samoa","AS");
        _stateList.Add("Arizona","AZ");
        _stateList.Add("Arkanas","AR");
        _stateList.Add("California","CA");
        _stateList.Add("Colorado","CO");
        _stateList.Add("Connecticut","CT");
        _stateList.Add("Delaware","DE");
        _stateList.Add("District Of Colombia","DC");
        _stateList.Add("Federated States Of Micronesia","FM");
        _stateList.Add("Florida","FL");
        _stateList.Add("Georgia","GA");
        _stateList.Add("Guam","GU");
        _stateList.Add("Hawaii","HI");
        _stateList.Add("Idaho","ID");
        _stateList.Add("Illinois","IL");
        _stateList.Add("Indiana","IN");
        _stateList.Add("Iowa","IA");
        _stateList.Add("Kansas","KS");
        _stateList.Add("Kentucky","KY");
        _stateList.Add("Lousiana","LA");
        _stateList.Add("Maine","ME");
        _stateList.Add("Marshall Islands","MH");
        _stateList.Add("Maryland","MD");
        _stateList.Add("Massachusetts","MA");
        _stateList.Add("Michigan","MI");
        _stateList.Add("Minnesota","MN");
        _stateList.Add("Mississippi","MS");
        _stateList.Add("Missouri","MO");
        _stateList.Add("Montana","MT");
        _stateList.Add("Nebraska","NE");
        _stateList.Add("Nevada","NV");
        _stateList.Add("New Hampshire","NH");
        _stateList.Add("New Jersey","NJ");
        _stateList.Add("New Mexico","NM");
        _stateList.Add("New York","NY");
        _stateList.Add("North Carolina","NC");
        _stateList.Add("North Dakota","ND");
        _stateList.Add("Northern Mariana Islands","MP");
        _stateList.Add("Ohio","OH");
        _stateList.Add("Oklahoma","OK");
        _stateList.Add("Oregon","OR");
        _stateList.Add("Palau","PW");
        _stateList.Add("Pennsylvania","PA");
        _stateList.Add("Puerto Rico","PR");
        _stateList.Add("Rhode Island","RI");
        _stateList.Add("South Carolina","SC");
        _stateList.Add("South  Dakota","SD");
        _stateList.Add("Tennessee","TN");
        _stateList.Add("Texas","TX");
        _stateList.Add("Utah","UT");
        _stateList.Add("Varmont","VT");
        _stateList.Add("Virgin Islands","VI");
        _stateList.Add("Virginia","VA");
        _stateList.Add("Washington","WA");
        _stateList.Add("West Virginia","WV");
        _stateList.Add("Wisconsin","WI");
        _stateList.Add("Wyoming","WY");
      }

      return _stateList;
    }

So there. Hope you’re happy.