0

I have an object that has keys and values as arrays. I tried to write a function and set up click function to each of them at once on document ready.

var settingsItems = {
    'featured': [
        'featured-1-heading',
        'featured-1-desc',
        'featured-2-heading',
        'featured-2-desc',
        'featured-3-heading',
        'featured-3-desc'
    ],
    'greeting': [
        'greeting-1-inputField',
        'greeting-2-inputField'
    ]
}

This is how my array looks like. And this is what I call in document ready:

for (var group in settingsItems) {
    settingsItems[group].forEach(function(x) {
        jQuery('#' + x).click(function () {
            switch (group) {
                case 'greeting':
                    var element = greetingForm
                    break;
                case 'featured':
                    var element = featuredForm
                    break;
                default:
                    alert("default alert");
            }
            settingsIconClicked(element, true, group)
        })
    })
}

To me, it should've worked but it is always returning 'greeting' as group variable, even when I click featured's elements.

senty
  • 12,385
  • 28
  • 130
  • 260
  • You need a closure as when the `click` event occurs the loop has finished, therefore `group` contains the last value of the array. See the question I marked as duplicate for more information – Rory McCrossan Nov 01 '16 at 11:08
  • I checked the top answers last example. He's using numbers and storing them in an array as far as I understand. However, I couldn't figure out how exactly to apply this in my case. Can I kindly ask you to add an answer below, to help me figure it out – senty Nov 01 '16 at 11:13
  • 1
    Here's a working example: https://jsfiddle.net/24dmpLxn/. Note that I made some of the variables in to strings as they were missing from your sample above. Also note that this would be made much, *much* simpler if you just put a class on all the relevant elements and didn't bother with the loop or lookup object. – Rory McCrossan Nov 01 '16 at 11:17
  • 1
    Here's a version which uses the simpler class method I mentioned: https://jsfiddle.net/24dmpLxn/1/ – Rory McCrossan Nov 01 '16 at 11:26
  • Huge thanks man! Nice tips. You saved me hours. Have a good day – senty Nov 01 '16 at 11:28

0 Answers0