4

In a jQuery function I am getting event on form's element click event. Now I want to get its html. How it is possible ?

For Example:

function(event, ID, fileObj, response, data) {
    alert( $(event.target) );            // output: [object Object]
    alert( event.target );               // output: [object HTMLInputElement]
    alert( $(event.target).html() );     // output: (nothing)    
}

I want to get form object who's element is clicked through event

Thanks

Student
  • 1,863
  • 9
  • 37
  • 50

3 Answers3

9

You can try event.target.outerHTML, however I'm not sure how well supported it is across all browsers. A more convoluted but sure to work solution would be to wrap the element in another element, then take the html of the parent element:

$('<div/>').html($(event.target).clone()).html();
Jack
  • 9,448
  • 3
  • 29
  • 33
  • Actually I want to append some hidden fields in this particular form. I am asking this question because there may be other same type of forms as well. is `event.target.outerHTML` suitable in this situation ? – Student Oct 09 '11 at 08:36
  • So you want to find the parent form element? $(event.target).closest('form'); – Jack Oct 09 '11 at 08:41
3

If your event is a click you can bind it using the click() method from jQuery. Use this to reach your element, like the code below:

$('#id').click(function(event){
  console.log($(this));
});
Max Shmelev
  • 3,774
  • 4
  • 26
  • 26
brolim
  • 41
  • 4
2

Most elegant solution I found is to simply use the properties on the event target. Here is an example how to detect the event source html tag. This example assumes you have bound a list item click event of unordered list with CSS class name myUnorderedList but you want to disable the default action if an anchor tag is clicked within the list item:

$('ul.myUnorderedList').on('click', 'li', function(event){ 

    console.log('tagName: '+ event.target.tagName);    //output: "a"
    console.log('localName: '+ event.target.localName);//output: "a"
    console.log('nodeName: '+ event.target.nodeName);  //output: "A"

    if(event.target.tagName == 'a')
        return; // don't do anything...

    // your code if hyperlink is not clicked
});
Emil
  • 2,196
  • 2
  • 25
  • 24