0

Can you please guide me how to replace a long javascript with a loop or something similar? I've to create some variables and after that call a method after each key press.

var list1 = new List('list1', options);
var list2 = new List('list2', options);
var list3 = new List('list3', options);
var list4 = new List('list4', options);
var list5 = new List('list5', options);
var list6 = new List('list6', options);
var list7 = new List('list7', options);
var list8 = new List('list8', options);
var list9 = new List('list9', options);
var list10 = new List('list10', options);
var list11 = new List('list11', options);

$('.search-field').on('keyup', function () {
    window.scrollTo(0, 0);
    list1.search($(this).val());
    list2.search($(this).val());
    list3.search($(this).val());
    list4.search($(this).val());
    list5.search($(this).val());
    list6.search($(this).val());
    list7.search($(this).val());
    list8.search($(this).val());
    list9.search($(this).val());
    list10.search($(this).val());
    list11.search($(this).val());
});
4

2 Answers 2

2

You can group your variables as array or object.

For example (variables in object):

const n = 11;
var lists = {};

for(let i=1;i<=n;++i) {
    lists['list'+i] = new List('list'+i, options);
}

$('.search-field').on('keyup', function () {
    window.scrollTo(0, 0);
    for(let i=1;i<=n;++i) {
        lists['list'+i].search($(this).val());
    }
}

Where object key is "variable name" and value for that key is just value

object[key] = value // write value
object[key]         // read value
Sign up to request clarification or add additional context in comments.

Comments

0

You can replace your code with this. Start with an empty array. Then use a for loop to add elements, then use another for loop to call function

const list = [];
for (let i = 0; i < 11; i++) {
  list[i] = new List('list' + i, options);
}


$('.search-field').on('keyup', function () {
  window.scrollTo(0, 0);
  for (let i = 0; i < 11; i++) {
    list[i].search($(this).val());
  }

});

1 Comment

Thank you, I tried your solution but I don't know why it is not working, when I replace it with the original code I wrote above it is working again!

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.