Child IFrame Page Interacting with Parent Page… Yeah I went there.

Example here.

File this under “Why?” but I wanted to see if a child could talk to a parent and then receive information back from the parent to update itself with. As usual, my lack of intelligent wording probably has you scratching your head… if you do that. Personally I don’t get that expression as when I’m confused I more than likely will grab a jar of peanut butter and start lathering up with it, but to each his own.

So here’s the idea, and this post is only the start.

You have a parent page, Parent.htm, with an iframe and you want the parent to do something and alert the child that something happened. For now, it’s actually really simple.

On the parent I have a method:

  function callMethod(text, methodDelgate) {
    if (methodDelgate != null) {
      methodDelgate(text);
    }
  }

And this simple markup:

  <iframe id="myFrame" src="Child.htm"></iframe>

Wow huh? Well on the child I have this:

  function callParent(text) {
    if (top.callMethod != null) {
	  top.callMethod(text, changeText);
    }
  }

This is easy. If the parent has the method, send the text through and a method to call when finished. What is this method? Well its:

  function changeText(text) {
    jQuery('#returnText').text(text);
  }

Which simply sets the text on some div to show it actually worked.

What happens when I click a button that calls callParent? It talks to the parent, the parent calls the passed in method, and the child updates itself.

Not sure this is rocket science, but there will be more on it as I add in the idea of a dynamically created pop up on the parent being used by the child. Until then, try not to be yourself. You embarrass your mother.

Get the jQuery DatePicker to Work With jQuery Modal Dialog

Being that I am the man, I thought I would share this little thingy with you because… well I’m the man.

So here’s the issue:  You have a date picker, a modal dialog, and you can’t see the calendar when you click on the icon and/or textbox. First thought, ‘WHY DOES THIS HAPPEN TO ME???!?!’ Second though, ‘I wonder if that tool knows how to get past this.’ Good news! I do. Turns out it has to do with the z-index. The modal dialog by default has a z-index of 1000ish when showing. (And any modal dialog “above that” will increase it’s z-index to match.) If the calendar isn’t higher than that, no go.

Now you might be using the jquery styles from the jquery site and might be putting your through your keyboard thinking about having to deal with that mess. However, it’s actually a simple fix in there… there being the ui.datepicker.css file.

  .ui-datepicker { width: 17em; padding: .2em .2em 0; z-index:9000; }

And there you have it. Now the calendar will show up in front of anything lower than 9000, and as everyone knows: Anything over 9000 is impossible.

jQuery Modal Dialog : Hide That Stupid X Button / Windows Close Button

This is quick one, so hold on to your… whatever.

Want to get rid of that X at the top right of the modal “Control”? Well here it is: (The bold part, moron)

     jQuery('#WaitingDiv').dialog({
          autoOpen: false,
          bgiframe: false,
          height: 150,
          width: 200,
          modal: true,
          open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); }
        });

And that’s really it. Just thought I’d pass that on to you, the consumer.

On a side note, the big movie thing is the canceling of Spiderman 4 or at least going in a new direction. As much as I don’t care, it might lead to my dream come true:

A spiderman movie based on the SNES classic: Spider-Man & Venom: Maximum Carnage. Uwe Boll, are you out there?

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>