0

So I am making a data entry program where the user presses buttons to generate new inputs (numbers text etc.) and when finished the lists are generally between 100-10000 items.

The program has been coming along well, but now I am at a point where one set of data entered must generate the coices for an array [1,2, . . .] which is part of a later set of data.

So what I have done is setup buttons with the ID based on the earlier inputs. (The whole data set is saved as a JSON)

And what I want to do is when the button is pressed it looks pressed and writes to an HTML element the ID of the button which will later be read and saved to JSON.

My problem is centered on getting the correct information back to the user.

function doStuff(container){
    for (var u = 0, c = someJSON.length; u < c; u++){
            var someButton = document.createElement('button');      
            someButton.id = someJSON.id;
            someButton.className = 'someButton';
            someButton.onclick = function() {
                writeIDToHTML(container,someButton,someButton.id);
            }
            container.appendChild(someButton);
    }
}

function writeIDToHTML(container,theButton,theID){
        console.log("theID")
        console.dir(theID)
}

This prints only the last ID in the loop. How do I get each ID to each button?

The other thing to do is to give the button a pressed look.

Bonus points if it is reversable.

JPack
  • 1
  • 1

1 Answers1

0

You should not add a listener on each element. The way to do it is adding a listener on the container and get the id of the clicked event (via event.target). This is called event delegation.

I could explain it, but this guys made a perfect answer to your question : http://davidwalsh.name/event-delegate

Btw, you should consider using a library like jquery to manipulate your DOM. It implements event delegation and advanced cross browser DOM manipulation utilities. For instance, you would not need to add a 'container' property since you can access it by the parent() method.

fabien
  • 2,228
  • 2
  • 19
  • 44
  • Thank you, I have read the tutorial and it helps. I also found a similar problem here: http://stackoverflow.com/questions/5040069/javascript-dynamically-assign-onclick-event-in-the-loop I have seen this method of generating the data dynamically but I do not understand the ins and outs of it. More tutorial links or example code is welcome, I have been stuck on this problem for a few days and am making my way past it slowly. – JPack Jul 10 '13 at 12:10