ltpitt
asked on
Best pratice to reduce code redundance on simple jQuery mobile page
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!
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!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
For the sake of future users I paste his solution here:
var j = {"Jan":"Gen", "Feb":"Feb"}
$(document).ready(function
$('.month').click(function
var month = $(this).attr("id");
window["dbChange" + j[month] ]();
});
})
function dbChangeGen() { alert("January"); }
function dbChangeFeb() { alert("February"); }