I would like to create a jQuery function that I can attach to form elements change() events, but have the function decide what to do based on the type (input, select, radio, password) of form element.
Problem is, I’m not sure of the best approach – write a large function that decides internally what to do, or write a sort of factory function that attaches an appropriate function to the element based on its type… am I reinventing the wheel? i.e. is there a default way of doing something like this in jQuery.
[Additional: if it influences the decision, the function needs to be called on load(), as well as say on change(), and it would be nice to be able to apply/call? the function just the once]
You can do what you want compartmentalized fairly easily with a few switches:
Now whether this is the best approach is certainly up for debate…it depends if you have a unique behavior for each, or some of them share behaviors, in which case you’ll probably want to define common functions in a closure and reference those, for example:
You could do this at least 20 ways, this is just a suggestion if each element and type has a specific behavior, which sounds like the case from your question. If it isn’t just ignore me 🙂