Page 1 of 1

[HELP] Assign click handlers in for loop

Posted: Wed Feb 03, 2016 2:37 pm
by Grandong
this my js code:

Code: Select all

        $.ajax({
        	type: "POST",
            url: "foo.php",
            data: {
                param: "foo",
            },
            success: function(data) {
            	var rest = data.data;
            	if (rest.length > 0) {
					for (var i = 0; i < rest.length; i++) {
						var prestult = [
							{
								Product: foo,
								Action: '<button type="button" id="gotobook'+i+'">foo</button>',
							}, 
						];
						DataTable.rows.add(prestult).draw();
					    $('#gotobook' + i).click( function(){
					      alert('you clicked ' + i);
					    });
					};
				};
            }
        })
	    ).done( function(a1){
	    	var data = a1[0].data.length;
	    	if (data > 0) {
	    		$('#loading-search').fadeOut('slow');
	    	} else {
	    		$('#loading-search').fadeOut('slow');
	    		$('.dataTables_empty').show();
	    		$('#ifnodata').fadeIn('slow');
	    	}
	    	console.log(data);
	    });
why if i click this button, i get wrong button id ? help me please...

Thanks Very Much...

Re: [HELP] Assign click handlers in for loop

Posted: Wed Feb 03, 2016 3:50 pm
by Christopher
The button has the id gotobook'1' while the jQuery click function attaches to #gotobook1.

Re: [HELP] Assign click handlers in for loop

Posted: Thu Feb 04, 2016 1:57 am
by Grandong
Christopher wrote:The button has the id gotobook'1' while the jQuery click function attaches to #gotobook1.
if i try inspect element, button id is correct

Code: Select all

id="gotobook1"

Re: [HELP] Assign click handlers in for loop

Posted: Thu Feb 04, 2016 11:36 am
by Christopher
The event handlers may not be able to see the buttons you added. Check for the syntax for live mode for .on() or .click().

Re: [HELP] Assign click handlers in for loop

Posted: Tue Apr 05, 2016 11:30 am
by thinsoldier
I can't say exactly why but I'd bet if you rearranged your code a bit it might work.

Instead of an anonymous function on "success:", actuall define that function and assign its name to success.

instead of id=gotobook1 just add a data attribute to the button tag: data-id=1.

Instead of creating multiple anonymous click even handlers in the for-loop, create just 1 function
and assign that to a parent tag what wraps the area where all of these buttons will be.

https://learn.jquery.com/events/event-delegation/

Let the click event handler function on the parent tag determine if its child or grandchild that was clicked is a button or not.
If it's a button, read that data-id attribute from the clicked button and work with that value.

I assume all the buttons do exactly the same job so they only need a single click handler function instead of a new (but identical) anonymous function created _for_each_ button.