I have to use same block of jQuery code several time in my page. Only changing selector names and url parameters.
My code look something like this:
$(document).ready(function () {
$("#year").change(function() {
var url = '';
var c = $("#category").val();
var d = $(this).val();
if(c.trim().length) { url+='&cat='+c }
if(d.trim().length) { url+='&mth='+d }
location.href="?p=summery"+url;
})
$("#category").change(function() {
var url = '';
var c = $(this).val();
var d = $("#year").val();
if(d.trim().length) { url+='&mth='+d }
if(c.trim().length) { url+='&cat='+c }
location.href="?p=summery"+url;
})
});
$(document).ready(function () {
$("#year2").change(function() {
var url = '';
var c = $("#category2").val();
var d = $(this).val();
if(c.trim().length) { url+='&cat='+c }
if(d.trim().length) { url+='&mth='+d }
location.href="?p=card"+url;
})
$("#category2").change(function() {
var url = '';
var c = $(this).val();
var d = $("#year2").val();
if(d.trim().length) { url+='&mth='+d }
if(c.trim().length) { url+='&cat='+c }
location.href="?p=card"+url;
})
});
$(document).ready(function () {
$("#year3").change(function() {
var url = '';
var c = $("#category3").val();
var d = $(this).val();
if(c.trim().length) { url+='&cat='+c }
if(d.trim().length) { url+='&mth='+d }
location.href="?p=chart"+url;
})
$("#category3").change(function() {
var url = '';
var c = $(this).val();
var d = $("#year3").val();
if(d.trim().length) { url+='&mth='+d }
if(c.trim().length) { url+='&cat='+c }
location.href="?p=chart"+url;
})
});
There are lot of code duplication. My question is, can any body help me to prevent this code duplication. Reason is, I have to this code block for lot of selectors and urls.
Hope somebody may help me out. Thank you.