0

Previously I have questions asking about beautify js codes in this link, but this time i'm not sure how to beautify this code below because im using words instead of index numbers. (bolted words are the reason it is NOT SAME as my previous question)

Original JS Code

//food
$("#food_east").keyup(function () 
{
    samefunction();
});

$("#food_west").keyup(function () 
{
    samefunction();
});

$("#food_north").keyup(function () 
{
    samefunction();
});

$("#food_south").keyup(function () 
{
    samefunction();
});

//beverage
$("#beverage_east").keyup(function () 
{
    samefunction();
});

$("#beverage_west").keyup(function () 
{
    samefunction();
});

$("#beverage_north").keyup(function () 
{
    samefunction();
});

$("#beverage_south").keyup(function () 
{
    samefunction();
});

And this is only food and beverage, i have not include others such as candy, snacks etc because its too messy to dump all my codes here. I can only come up with this solution, is there better solution?

var compass = ["east", "west", "north", "south"];

    for(var i=0; i<3; i++)
    {
        var name = "#food_";
        name += compass[i];

        $(name).keyup(function () {
            samefunction();
        });

        var name = "#beverage_";
        name += lokasi[i];

        $(name).keyup(function () {
            samefunction();
        });
    }
LearnProgramming
  • 814
  • 1
  • 12
  • 37

2 Answers2

1

This is why classes where invented... give every element that same class and bind the function to that class.

Another way could be to use the selector ‘starts with’: $(‘[id^=“food_”]’).keyup...

patrick
  • 11,519
  • 8
  • 71
  • 80
1

Use a class, instead of one unique identifier per element. A class is like a group name. All elements with that class can be selected at once.

$(".someClass").keyup(function () {
    console.log("Keyup event!")
    // Do stuff
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="someClass" type="text" />
<input class="someClass" type="text" />
<input class="someClass" type="text" />
<input class="someClass" type="text" />
<input class="someClass" type="text" />
<input class="someClass" type="text" />
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63