Stephen Jenkins
Stephen Jenkins

Reputation: 1836

Are there ways to optimise multiple if, else if, else statements?

Here's my code, is there anyway to somehow loop through the if, else if and else statements to dynamically populate them somehow (without so many statements, or is this considered good practice)?

$('input').each( function () {

    var self = $(this)

    if ( self.attr( 'type' ) === 'email' && supportsInputType ( 'email' ) ) {
            self.data( 'fallback', 'email' )
    } else if ( self.attr( 'type' ) === 'url'  && supportsInputType ( 'url' ) ) {
            self.data( 'fallback', 'url' )
    } else if ( self.attr( 'pattern' ) && supportsAttr ( 'pattern' ) ) {
        self.data( 'fallback', 'pattern' )
    }

})

I've omitted my other functions as concentrating on the if/else etc. Thanks for any advice.

Upvotes: 0

Views: 123

Answers (2)

Blender
Blender

Reputation: 298136

If you make supportsInputType properly handle any type, you could just do something like this:

$('input[type]').each(function() {
    var $this = $(this);

    if (this.type !== $this.attr('type')) {
        $this.data('fallback', type);
    }
});

Upvotes: 4

elclanrs
elclanrs

Reputation: 94101

I would try to craft a selector that grabs the inputs by attribute straight away and get rid of supportInputType. Something like this (untested):

var attrs = ['type=email','type=url','pattern'];

$.each(attrs, function(i,attr) {
  $('input['+ attr +']').data('fallback', attr.replace(/.+=/,''));
});

That should probably work with your current code.

Upvotes: 0

Related Questions