Solved

Best pratice to reduce code redundance on simple jQuery mobile page

Posted on 2013-05-14
2
241 Views
Last Modified: 2013-05-15
Hi all!

I have a simple jQuery Mobile page where I have 12 buttons.
Each button is a month of the year (Jan, Feb etc etc).

I want that if the user taps on a month a record is created in a mysql database for the month pressed.

If the user press the same month button again the record is deleted.

Right now (being a beginner in his learning phase) I'd do it like:

$('#Jan').click(function(){
        dbChangeGen();
        });

$('#Feb').click(function(){
        dbChangeFeb();
        });

And each function will do its ajax post to php that'll insert or delete the data.

Is there any way not to write 12 almost identical functions?

I don't need specific code (even if a snippet to clarify is always welcome :) ) but I'd need to understand how a real programmer would handle a similar task to improve and learn better.

Thanks!
0
Comment
Question by:ltpitt
2 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39166659
0
 
LVL 1

Author Closing Comment

by:ltpitt
ID: 39167220
Simple and very clean!

For the sake of future users I paste his solution here:

    var j = {"Jan":"Gen", "Feb":"Feb"}
    $(document).ready(function() {
        $('.month').click(function(ev){
             var month = $(this).attr("id");
             window["dbChange" + j[month] ]();
        });
    })



function dbChangeGen() { alert("January"); }
function dbChangeFeb() { alert("February"); }
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've been asked to discuss some of the UX activities that I'm using with my team. Here I will share some details about how we approach UX projects.
An enjoyable and seamless user experience can go a long way on an eCommerce site. While a cohesive layout and engaging copy play roles in creating a positive user experience, some sites neglect aspects that seem marginal but in actuality prove very …
This video teaches users how to migrate an existing Wordpress website to a new domain.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question