0

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.

3
  • Create a function that takes ID and urlFragment arguments Commented Sep 7, 2016 at 5:53
  • @jedifans, can you kindly show me an example? Commented Sep 7, 2016 at 5:55
  • 1
    Better asked in CodeReview.SE. Commented Sep 7, 2016 at 5:55

3 Answers 3

2

Extract the common code into a function:

function navigateBasedOnInput(monthInput, categoryInput, urlFragment) {
    var url = '',
          category = $(categoryInput).val(),
          month = $(monthInput).val();

    if (category.trim().length) {
        url += '&cat=' + encodeURIComponent(category);
    }
    if (month.trim().length) {
        url += '&mth=' + encodeURIComponent(month);
    }

    location.href = "?p=" + encodeURIComponent(urlFragment) + url;
}

$(document).ready(function () {
    $("#year, #category").change(function() {
        navigateBasedOnInput('#year', '#category', 'summery');
    });

    $("#year2, #category2").change(function() {
        navigateBasedOnInput('#year2', '#category2', 'card');
    });

    $("#year3, #category3").change(function() {
        navigateBasedOnInput('#year3', '#category3', 'chart');
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Never trust user input. A user might have put & in the form field, which would cause &cat=the&st&mth=2. encodeURIComponent() escapes any & characters and a few more.
1

Try moving the common stuff out into a function.

function commonFunc(c, d, pStr) {
    var url = '';
    if (d.trim().length) {
        url+='&mth='+d;
    } 
    if (c.trim().length) { 
        url+='&cat='+c;
    } 
    return pStr+url;
}

Then in the change function it will be:

$("#year").change(function() {
    var c = $("#category").val(); 
    var d = $(this).val(); 
    location.href = commonFunc(c, d, '?p=chart');  
  });

Plus you can also put all the listeners in one ready function

[EDIT] It's a good habbit to add ; to the end of your statements

1 Comment

he can also put the 'twin' element id on data-attribute for example on the #year element `<select id="year" class="general" data-element="category" /> and then can put an event listener on the class and get the other element by the data attribute.
0

maybe you can do it like this:

var urls={
  year1:"",
  year2:"",
  year3:""
};
["year1","year2","year3"].forEach(function(e){
    var self = $("#"+e);
    self.change(function(){
        var url = urls[e], 
        c = self.val(),
        d = $(this).val(); 
        if(c.trim().length) { url+='&cat='+c } 
        if(d.trim().length) { url+='&mth='+d } 
        location.href="?p=card"+url;  
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.