Section 4: Implement jQuery Part 1 of 2

Overview: Today we will do nothing but write some jQuery to make a small feedback form for a website. Thie code we are about to walk through can be significantly improved, so keep that in mind. Overall though, we are going to get the job done with some decent looking code, and next week we will turn our code we make today into a full blown plugin that anyone can use. The entire code for this section is in jQuery, so that when we refactor next week, we can change alot of jQuery into plain old Javascript.

Our Assignment

Ok so we work on an application, and the product owner wants some kind of a feedback form for a page on the site. They want it to be very basic, the only real requirement are that it have 1 set of radio buttons for the "reason", a text area for comments, and that the options in the group me dynamic and pulled from the database. They client has an admin panel and can add, edit, and delete options from a table in the database. Should be pretty easy.

Live example of what we want

Into the Code

Let's walk through the code that powers this little dialog and see what it is doing.


Our HTML is going to be very basic:



And now for the jQuery:



So What is Wrong With This Code?

The code is not necessarily wrong... it executes and does what it is supposed to just fine. The code itself is not bad, but here is some things we did not do so well on:

  • Modal comes from the server side - We are depending on the server to give us a very specific modal. What if I want to use this on another project with a different server?
  • Titles and names are not configurable - We were off to a good start with the
    settings.title
    , but we kind of fell off after that. If we want to re-use this, we may not want all the titles to always be the same
  • Not HTML agnostic - For our jQuery to work, we need to have very specifically named elements in the DOM, regardless of if the HTML came from the server side or not, we have no wiggle room with element selectors, everything must match exactly
  • A lot of jQuery abuse - Do we really need to use the
    $
    that much? Or can we do our browser a favor and just use plain old JS instead sometimes?

Next Week...

Next week we will refactor this code to be reuable, as lightweight as possible, and turn our feedback form into a real deal plugin that can be used on any project that has Bootstrap and jQuery. If we wanted to go that far, we could get rid of our jQuery and Bootstrap dependencies as well, however then our plugin is more than likely going to require a CSS file with it (if not Bootstrap) and this will be a lot more work. Take a look at the code we did today, and think about what we could have done better.