kejo
kejo

Reputation: 161

How to condense hardcoded jQuery code to smaller generic code?

I have a code that works perfectly fine because it is hardcoded but extremely large. I would like to simplify this code to make it general and of course smaller. Does anybody know how to do this? Since it is so large I will shrink it down for this question.

    var theform1 = $('#form1').find('.state option');        
    var stateForm1 = Object.keys(localStorage).filter(key => key.endsWith('-state1'));
    var stateChoice1 = JSON.parse(localStorage.getItem(stateForm1));

    var theform2 = $('#form2').find('.state option');        
    var stateForm2 = Object.keys(localStorage).filter(key => key.endsWith('-state2'));
    var stateChoice2 = JSON.parse(localStorage.getItem(stateForm2));

    var theform3 = $('#form3').find('.state option');        
    var stateForm3 = Object.keys(localStorage).filter(key => key.endsWith('-state3'));
    var stateChoice3 = JSON.parse(localStorage.getItem(stateForm3));

    if (localStorage.getItem(stateForm1)) {            
        $(theform1).empty();
        $(theform1).val(stateChoice1).append(`<option value="${stateChoice1}">${stateChoice1}</option>`).trigger('window.load');                    
    }; 

    if (localStorage.getItem(stateForm2)) {            
        $(theform2).empty();
        $(theform2).val(stateChoice2).append(`<option value="${stateChoice2}">${stateChoice2}</option>`).trigger('window.load');                    
    };

    if (localStorage.getItem(stateForm3)) {            
        $(theform3).empty(); 
        $(theform3).val(stateChoice3).append(`<option value="${stateChoice3}">${stateChoice3}</option>`).trigger('window.load');

    };        

The HTML markup is as follows:

    <form id="form1" autocomplete="off">
   <select id="country1" class="country" name="country">
    <?php include("countryAjaxData.php"); ?> 
   </select> 
   <select id="state1" class="state" name="state">
    <option value="" selected="selected">Select state</option>
   </select> 
   <select id="city1" class="city" name="city">
    <option value="" selected="selected">Select city</option> 
   </select>
  </form>
  <form id="form2" autocomplete="off">
   <select id="country2" class="country" name="country">
    <?php include("countryAjaxData.php"); ?> 
    </select> 
   <select id="state2" class="state" name="state">
    <option value="" selected="selected">Select state</option>
   </select> 
   <select id="city2" class="city" name="city">
    <option value="" selected="selected">Select city</option> 
   </select>
  </form>
  <form id="form3" autocomplete="off">
   <select id="country3" class="country" name="country">
    <?php include("countryAjaxData.php"); ?> 
   </select> 
   <select id="state3" class="state" name="state">
    <option value="" selected="selected">Select state</option>
    </select> 
   <select id="city3" class="city" name="city">
    <option value="" selected="selected">Select city</option> 
   </select>
  </form>

Upvotes: 1

Views: 74

Answers (2)

T&#226;n
T&#226;n

Reputation: 1

Maybe you're looking for this compressed version:

$('#form1,#form2,#form3').each(function () {
    var index = this.id.substring(this.id.length - 1, this.id.length);
    var stateForm = Object.keys(localStorage).filter(key => key.endsWith('-state' + index));
    var stateChoice = JSON.parse(localStorage.getItem(stateForm));

    if (localStorage.getItem(stateForm)) {
        var theform = $(this).find('.state option').empty();

        theform.val(stateChoice)
                .append(`<option value="${stateChoice}">${stateChoice}</option>`)
                .trigger('window.load');
    }
});

If you have more than 10 forms with the index increasing from 1 to 99 or 999... You can edit the way to name your form id to: form01 form02 form03 or form001 form002 form003...

Then, because all of the id names start with form, you can update the selectors like this:

Changing $('#form1,#form2,#form3') to $('[id^="form"]'). That selector means: selecting some element(s) which contains the id starts with form.

Lastly, if your form id following by 2 digits (form01), you update the line to get the index to:

var index = this.id.substring(this.id.length - 2, this.id.length);

You can do the same way for the ids following by 3 digits (form001):

var index = this.id.substring(this.id.length - 3, this.id.length);

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Loop over all the select.state and get the number from the parent form.

Something like:

$('select.state').each(function() {
  const $sel = $(this),
    formNum = $sel.closest('form').attr('id').replace('form', ''),  
    stateForm = Object.keys(localStorage).find(key => key.endsWith(`-state${formNum }`)),
    stateChoice = localStorage.getItem(stateForm);


  if (stateChoice) {
    $sel.append(new Option(stateChoice. stateChoice))
      .val(stateChoice)
      .trigger('window.load');
  }

})

Note I changed filter() to find() for the keys since filter returns an array

Upvotes: 0

Related Questions