www.webdeveloper.com
Results 1 to 4 of 4

Thread: how to add events dynamically using jquery

  1. #1
    Join Date
    Nov 2011
    Posts
    22

    how to add events dynamically using jquery

    in my project i m creating html DOM elements dynamically using JQUERY.
    All the data that required for creating are in JSON structure.
    eg:

    Code:
    [ 
    { 
    "node": "INPUT", 
    "id": "BTN", 
    "onclick": "alert("hi")", 
    "type": "button" 
    } 
    ]
    so whatever passing to the function as event name should be add to the element.

    I tried to add events to the HTML DOM variable as shown below

    Code:
     
    jQuery(DOMelem).bind("onclick", alert(hi));
    DOMelem is the HTML element that created dynamically using jquery. i need to bind the events to this.

    but im getting error while executing this.
    Code:
     
    <TR id=1x1x1x1x1 jQuery171010988482103845665="1"></TR>
    any idea why it happens?

  2. #2
    Join Date
    Feb 2011
    Location
    Waterloo, Ontario, Canada
    Posts
    80
    "Hi" needs to be in quotes in your alert for starters.

  3. #3
    Join Date
    Apr 2010
    Location
    Salem,Ma
    Posts
    623
    please show an example of the DOMelem variable.
    Also where are you using the json data in this example?
    - and What error are you getting? you have shown an empty row element, but no errors.

  4. #4
    Join Date
    Nov 2011
    Posts
    22
    Code:
    var jsonData = [{
            "node": "INPUT",
            "id": "1x1x1",
            "onclick": "alert('hi')",
            "type":"button"
         
        }];
    function test(tmp)
    {
        alert(tmp)
    }
        DOMelem = document.createElement(jsonData[0].node);
        jQuery(DOMelem).attr("type",jsonData[0].type);
        jQuery(DOMelem).attr("id",jsonData[0].id);
        $("body").append(DOMelem );
        $("#" + DOMelem.id).bind("click",test(1));
    this is a sample code.

    i dont know how to attach event to a dynamically created element.
    so in my code in the page load itself the function test will called but not while clicked on the button.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles