Set a value based on the presence of a class name (with jQuery)

In working on the web app that I’m employed to work on, I needed to check for the presence of a class name out of a few different possibilities so I could set the value of a variable based on that. If I only had to do this once or twice, and if there were only two options, I’d simply do:

var value = $('#element').hasClass('opt1') ? 'opt1' : 'opt2';

Piece of cake, right? Well, I had to do this many times, and once or twice there were more than two options. So I made a little function that will iterate over an array of possible values and check for a class name with that value, then return it.

Here’s what I came up with (yes, it uses jQuery because the web app uses it, so why not):

//"APP.utils" is the namespace where this function will live.
var APP = APP || {};
APP.utils = APP.utils || {};

APP.utils.getValueByClass = function( $container, values ){
    var val='';
    $.each(values, function( i, v ){
        if ($container.hasClass(v)){
            val = v;
            return false; // exit if we have a match
        }
    });
    return val ;
};

Here’s how you’d use it:

The HTML:

<!-- the 'us' class name indicates the date format, the placeholder directs the user -->
<input type="text" id="start" name="start" class="date us" placeholder="08/28/2014">
<p id="success"></p>

The JavaScript:

var format = APP.utils.getValueByClass( $('#start'), ['us','iso','eu'] );

The arguments are:

  1. a jQuery DOM object (not a string for the id or selector, a full jQuery object)
  2. an array of class names to look for (the first one found will be the returned value)

Now you’ve got a value for the format var to possibly use to determine how to split up the parts of a date input for form submission, which I will show in a later post.

Advertisements

One thought on “Set a value based on the presence of a class name (with jQuery)

  1. Pingback: Example: Get date format by class name and submit data via AJAX (with jQuery) | Error 601

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s