0

i have a mainbox inside which some more boxes are dynamically generated.

// first time retrive
$.post("dataretrive.php", {
    }, function(data, status) {
        document.getElementById('mainbox').innerHTML = data;
        timer();
    });

then on click on these subboxes some i am implementing some functionality

$('.boxes-main').unbind('click').on('click', '.subbox', function(e){
    var value1 = $(this).attr('data');
    var value2 = $(this).attr('data2');
    var value3 = $(this).attr('data3');
    var value11 = $(this).attr('data4');
    var value12 = $(this).attr('data5');
    var value13 = $(this).attr('data6');
...... // some more functionality with these data which i think doesn't matter for this question for this question
    });

As i want to implement shortcuts to these subbox like when user press 1 it trigger a click event on that box. I also have ID's associated with that. like box1 , box2, box3 and so on. and i am trying to put a click event of that box when key 1 is pressed.

$(document).keypress(function(e) {
  if(e.charCode == 49) {
$('#box1').click();
  }
});

I had also tried trigger function , $("boxes-main #box1').click(); but nothing works because contents are dynamically generated. someone tell me please how to implement manual click event on dynamically generated element.

and don't get confused between boxes-main and mainbox both are class and id of same div element.

3
  • Please show an example of the dynamically generated elements' HTML. If you can select it you can trigger a click with .click(). If you can't select it, due to another problem, that may be the issue. Commented Feb 10, 2016 at 14:30
  • Also note: you should use off with on for consistency (not unbind). It may work but it is confusing to readers :) Commented Feb 10, 2016 at 14:32
  • Based on your comment, you are targeting the wrong element with your delegated event handler. Added explanation below. Commented Feb 10, 2016 at 14:40

1 Answer 1

1

Based on your comment:

and don't get confused between boxes-main and mainbox both are class and id of same div element.

It is not the click generation that is broken, but you are targeting the wrong ancestor in your delegated click event handler. Go higher up the ancestors to a non-changing element. document is the best default if nothing else is closer.

$(document).on('click', '.subbox', function(e){

Notes:

  • Don't mix bind with on. Use off instead
  • You don't need off/unbind at all in this example
Sign up to request clarification or add additional context in comments.

Comments

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.