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!

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.

ASP.Net MVC: Quick Overview of Controller Structure

Wow, that’s a mouthful far as titles go, but couldn’t think of a better way to say it. Now what I’m about to go through is the “system” I have found that works pretty well when it comes to structuring controllers knowing that there will be asynchronous operations. Why is that a big deal? Well where you put certain methods can depend on which controller actually owns the action.

When I started using MVC, I had some issues on figuring out how to build controllers so that they made sense from a structural point of view. I slightly touched on it but I wanted to show where I progressed to in the vain hope that I can help prevent stumbling on your part.

One thing to be noted is the asynchronous part. I’ve become a firm believer that MVC is pointless without asynchronous operations. Why? Simply put, you can use them or you can come up with some annoying post and redirect for any create, update, or delete operations. If you’re going to do that, you might as well just be institutionalized because you are one masochistic mother f—er. For everyone else in the happy world, go with something like jQuery that makes it real easy to perform said operations.

With the last paragraph in mind, the part I had trouble with the most was figuring out where the actions go. You see, when I started using MVC, I grouped stuff in an ultra simple manor. Say I have a site for handling pictures. Well there would be a view controller that would have anything to do with viewing images and an admin controller that took care of the uploading, changing, deleting, ecting. As you can imagine, this was not what you might call ideal.

Once I got a feeling for MVC and how it worked, I started having things a little more separated but still didn’t feel right. I had actions for viewing a list of images on the image controller no matter if public or admin side which wasn’t really ideal to me since it kind of blurred what was public and what was restricted from a conceptual point of view.

It wasn’t until I started thinking in terms of unit testing that it started to make more sense. If I were creating controllers as if they were classes instead of pages like with WebForms, maybe it would work out better. Seems real profound right? Well it was at the time since I still had WebForms state of mind. All of a sudden, it made way more sense on how the controllers should be set up. In an odd way, the controllers almost became almost business layer like. If I wanted to update an Image, there would be an Update method on the image controller responsible for taking in the changes, validating, and dealing with the entity objects. Everything that had to do strictly with displaying information would be handled by a display controller like the before mentioned Admin controller. So something like:

Controller Outline

As you can see, the Admin controller has something to show all users. The User controller has the methods for things like updating, creating, and validation. Basically anything that would change an image is on one controller. Anything for showing it on the main section controller. That is, a controller that embodies an overall concept like say an Admin section of a site or possibly a controller for viewing galleries.

The sequence of events (bad word choice…) would be something like:

Open Admin/UserList/
Admin controller uses User Entity to retrieve list
Admin View shows User List
User clicks delete button/link on Admin View
Javascript/jQuery method invoked to send id to User/Delete
User controller receives id
User controller validates id to make sure it is valid
User controller validates current user to see if allowed to delete
User entity Delete method invoked by User Controller
Result of Delete Method is returned by User Controller (JSon preferably)
Admin View displays the result

Treating controllers like classes (and the use of anonymous actions) allows a very clean separation of actions resulting in a nice logical layout. Beyond this, it also allows for a greater separation between controllers which means its possible to do multiple parts of the entire project in parallel.

Maybe this is just stating the obvious, something I’m pretty good at, but my hope was to give a quick over view of laying out controllers for those who are just starting out.

jQuery: Find All Checked Checkboxes

So this is sort of a repeat of another post, but I figured it has some use on its own.

Say you have this:

  <div>
    <input type="checkbox" name="JqueryIdList" value="1"  />
    <input type="checkbox" name="JqueryIdList" value="2" />
    <input type="checkbox" name="JqueryIdList" value="3" />
    <input type="checkbox" name="JqueryIdList" value="4" />
  </div>
  <div onclick="getIds('JqueryIdList');">
    CLICK
  </div>

And you need the getIds method to find all the checked checkboxes from that markup. Well it’s actually fairly simple, or at least it wil be once I enlighten you. I should get paid for this…

  function getIds(checkList)
  {
    var idList = new Array();
    var loopCounter = 0;
    //find all the checked checkboxes
    jQuery("input[name=" + checkList + "]:checked").each
    (
      function()
      {
        //fill the array with the values
        idList[loopCounter] = jQuery(this).val();
        loopCounter += 1;
      }
    );
    ...
  }

The important part is this:

 jQuery("input[name=" + checkList + "]:checked").

As you can see, it is very simple. Give it the name of the checkboxes, add on the “:checked” and boom you have a list of checked checkboxes. Could it be more simple? I think not.

ASP.Net MVC How To Handle Multiple Checkboxes With Views/Actions… jQuery too!

Just a note, this is kind of an add on to this post but it’s a much more simple (HOSTED) example and also deals with doing the whole check box thing with jQuery.

So one of the things I ran into some what recently was a grid… a grid with a death wish and a thirst for revenge. It also has a bunch of check boxes to allow multiple row deletes.

Now there might be a moment of panic and doubt (Or doubt and panic, everyone reacts differently) when you realize you no longer have those cushy grid postback events. WHAT ARE YOU GOING TO DO???? Well first you’re going to feel disgust over your profuse sweating, cause lets be honest you’re pretty gross. Then you’re going to read on and find that all your panic, fun as it can be, was for nothing. Why? Because you have me… and not in some weird love kind of way because I don’t even know you. More of a “You can count on me because I’m like that cool older brother you never had and because of which you ended up a social degenerate ie a programmer” kind of way.

Now to start I’ve already hosted both the code and a working example:

Actual running thing on teh webz.

Hosted code

Because I’m such a nice guy. (And that’s true, I can list at least five people who aren’t my mom who can attest to that.) However, I wouldn’t be the nice guy that I am if I weren’t going to at least explain some of the code.

There are two ways I handle this situation in the example I hosted, one is with a form, action, and post back. The other is with jquery and an asynchronous call. Both are actually pretty easy to pull off.

First let’s look at the post back version. The mark up looks a little somethin’ like dis:

  <form action="/Test/CheckForIds/" method="post">
    <div>
      <input type="checkbox" name="IdList" value="1"  />
      <input type="checkbox" name="IdList" value="2" />
      <input type="checkbox" name="IdList" value="3" />
      <input type="checkbox" name="IdList" value="4" />
    </div>
    <div>
      <input type="submit" value="go" />
    </div>
  </form>

Looks like your standard form and if you’ve used MVC at all, you should be used to seeing something like that. The only thing of interest is that the checkboxes don’t have ids and do share the same name. There’s a good reason for the second one. Here’s the action method:

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult CheckForIds(Int32[] idList)
  {
     return View(idList);
  }

Now it makes more sense, doesn’t it? The name attribute on the checkbox directly corresponds to the name of the array parameter. THAT’S AMAZING!!!1 Actually, kidding aside it is kind of nice. Not only does it match the checkboxes to the parameter, it also treats the values of the checkboxes (Checked ones) as a list of integers. Pretty slick.

And honestly, that’s about all it takes for traditional posting.

Now for the jQuery part:

  <div>
    <input type="checkbox" name="JqueryIdList" value="1"  />
    <input type="checkbox" name="JqueryIdList" value="2" />
    <input type="checkbox" name="JqueryIdList" value="3" />
    <input type="checkbox" name="JqueryIdList" value="4" />
  </div>
  <div onclick="getIds('JqueryIdList');">
    CLICK
  </div>

Wow, looks about the same. Go figure. Well that’s pretty much because the way hard part is the javascript itself.

  function getIds(checkList)
  {
    var idList = new Array();
    var loopCounter = 0;
    //find all the checked checkboxes
    jQuery("input[name=" + checkList + "]:checked").each
    (
      function()
      {
        //fill the array with the values
        idList[loopCounter] = jQuery(this).val();
        loopCounter += 1;
      }
    );
    //Send the list off
    jQuery.getJSON("/Test/CheckForIdsJson/", { idList: idList }, idsGotten);
  }

Ok maybe it wasn’t that hard or hard at all. But um… And here’s the action method:

  [AcceptVerbs(HttpVerbs.Get)]
  public ActionResult CheckForIdsJson(Int32[] idList)
  {
    JsonResult result = new JsonResult();
    result.Data = idList;

    return result;
  }

So again, the same signature. Amazing huh?

Side note:

When I was eating this morning in front of the television (Chocolate shredded mini wheats if you must know.) I came upon the good ole classic Iron Eagle. I never really thought about how utterly f-ing insane that movie was until now though, mostly because I haven’t seen it since I was a kid. I guess back then I could completely buy into the idea of some 17 year old, who can’t make it into the Air Force Academy, suiting up and learning to use (At the time) the most complicated fighter the US had to offer within what? one whole montage, steal a 18 million dollar plane (Planes were cheap back then), fly into crazy dangerous territory, get past who knows how many trained professionals, save his dad, and nothing really comes of it. Actually I think if I remember (as I didn’t get to watch the whole thing this time) he gets a place in the academy from this. IT’S A COMPLETELY BELIEVABLE STORY! The best part about it is that apparently between the time of the first and second movie his skills had depleted so fast that he gets popped at the beginning of the second one. I guess without the Saving Dad mojo, he’s just not the same. Tip your glass to good ole Thumper.

I really miss the 80s where movies didn’t really need to make any sense as long as they had some soundtrack filled with crazy obscure bands playing at random times in the movies itself followed by the movie characters commenting how great the music is.

ASP.Net MVC: Show Picture Dynamically Using jQuery

Ready for the next step to this guy? Can’t sleep lately because of it? Ignoring your day to day tasks due to anticipation? Well wait no longer. I have just the cure for you. In fact, steady use has shown to improve both self esteem and popularity. Behold Jquepictuax:

function showPicture(imageHolder, id)
{
  jQuery(imageHolder).attr("src", "/Photo/ShowPhoto/" + id);
}

And you can’t forget to try:

<img id="holder" alt="" />
<div onclick="showPicture('#holder', '79');">Show!</div>

And with that your life will be far better than it was before. You can once again start enjoying the simple things in life. Enjoy the birds singing, the sun setting, and those noisy little things that run around your house.

Disclaimer: Id may vary. Image results also very. Though proven to be better when tested again a placebo, Jquepictuax may not improve your self esteem or make you more popular. Jquepictuax is not guaranteed to improve your life in any way. Use Jquepictuax in small quantities. People with low blood pressure or who are pregnant should avoid using Jquepictuax. If you consume more than 3 alcoholic drinks per day, please seek medical attention before use. May cause certain side effects such as dizziness, nausea, overwhelming chills, headaches, muscle soreness, dry mouth, light headedness, sleepiness, drop in appetite, and death. If you notice any these side effects, stop use of Jquepictuax immediately and seek medical attention. Please consult physician before Jquepictuax use.

You happiness is right around the corner, why not turn it with Jquepictuax?

To Async or Not To Async… That is the ReWritten Cliche Quote.

One of the things I’ve been wondering as a of late, besides why Micheal Bay still is allowed to make movies… and no money is NOT and excuse, is whether it’s better to just load and entire page and hide/show stuff on some click OR only load what’s shown and have said click handle loading the stuff through Asynchronous Calls and Json.

I bet that made sense!

Here’s the situation, I have a blog thing I’m working on and it allows for multiple blogs per site. The “splash” page, if you will, looks like this:

BAT_BlogSplash1

And when you click “Newest” it looks like this:

BAT_BlogSplash2

As you can see, Newest brings up a pop out div thing that shows the latest post.

Side note, I was going to have it just show the first X characters of the post as a teaser, but turns out that if there is any broken HTML because of that, IT’S A HUGE PAIN TO FIX. Something like <div> this is something that <di… OH SNAP THE DIV IS BROKEN! ALERT! ALERT! So this was a “solution”.

Originally I had it loading the needed post in it’s respective pop out div and just hiding all of them. Then it would show the post when the Newest “button” was clicked. Then it dawned on me that this might be silly since only one is going to be open at a time. Why send the client a ton of unneeded html? So, I moved on to using jQuery/Json to grab the needed post data when the Newest “button” is clicked. Then I just populate the pop out div with the returned information as it opens… or whenever it gets back to the client. Can’t always assume it will be there immediately. Interweb can be slow at times.

Anyways, this brings up an issue: Am I better off with the first or second solution? Given that all things are equal, it seems like a better idea to have the jQuery solution due to the fact you aren’t sending useless html to the client. This will most definitely help with initial load time for the client. Only problem is, that jQuery method is run every time one of the Newest “buttons” is pressed meaning you could have an infinite amount of requests per person. I suppose this is a matter of gambling really.

Do I go with full html and because I assume the user will look at all the latest posts anyhow and therefore cut down the needed requests?

Do I go with the jQuery method because more often than not, users will not look at all the latest posts OR at least will take some time in between the Newest “button” pressing so that it’s ok there might be a ton of requests over time?

At this point I think the second is the way to go, but it’s most likely situational. Time will tell.

jQuery Whack-A-Mole… Timer, Hide, Slide, and Fun

So I’ll just straight up file this under “I really shouldn’t have” and not bother asking for forgiveness. For some reason I had it in my mind I wanted to see if I could take the stuff I learned from this guy and this guy and see if I could make a simple Whack A Mole game with just jquery and the three include files. (jquery, jquery UI, and jquery Timer) Not thinking of the massive consequences such a thing might bring, I pushed on in the name of science.

So with no further build up or stupidity (I used that all up in building this game) I give you jQuery WHACK A MOLE which oddly enough has somehow clawed it’s way into my hosting here. So if you’re foolish enough to actually want to know how it works, there are plenty of comments in the script files. Just don’t blame me for any loss of intelligence.

I might actually take this to the next horrifying level and make it an mvc application. Not sure I… no… THE WORLD can take it.