Balraj Singh
Balraj Singh

Reputation: 3471

Unable to pass 'this' value from one javascript function to another?

I am calling a Javascript function from div onClick method

<div onClick="sample_1(this)" />

from this sample_1 method i am creating a new div dynamically and adding an onclick event in that div and trying to pass the value of 'this' got from the parameter of the sample_1 function but i am not able to pass the value of 'this' to the second method:

function sample_1 (divSelected) {
    if (!$(divSelected).attr('disabled')) {
       $('div[id=sample_1]').append("<div id='sample_1_1" + categoryID + "' class='selectedActivityCategory' style='background-color:#d9eaf7;' > <img  src='../Images/close.png' onclick='sample_2(" + divSelected.value + ");' /> </div>");
    }

}


function sample_2(divSelected)
{
/* Some Code */
}

When i am looking into IE developer tool then this dynamic div "sample_1_1" in its onClick method instead of passing the object divSelected value its just writing:

sample_2([object HTMLDivElement]);

How can i pass the object divSelected from sample_1 to sample_2?

I am trying to access the reference of the first div that is calling and passing its reference as this to method sample_1_1 and from there i am creating a new div and onclick event of that created div i am trying to pass the same reference of 1st div to the onclick method of the created div in sample_1_1 method.

Upvotes: 1

Views: 1317

Answers (2)

Asterisk
Asterisk

Reputation: 3574

As said in comments, div element does not have a value property. If you want to access text within div use innerHTML. The parameter passing actually works fine, just check you if statement.

function sample_1 (divSelected) {
    alert(divSelected.innerHTML);
    sample_2(divSelected);

}


function sample_2(divSelected){
    /* Some Code */
    alert(divSelected.innerHTML);
}

Upvotes: 1

Jules
Jules

Reputation: 7223

I don't understand what you are trying to do. The regular Javascript this does not have a value property.

If you are trying to get the contents of the div, you are mixing up this and $(this), because through JQuery you can get the contents of a div (not through value) but by doing $(this).html().

So a possible solution would be something like:

<div id="yourdiv">Content...</div>

$(document).ready(function() {
   $('#yourdiv').click(function() {
      sample_1($(this));
   });
});

function sample_1(div_selected) {
   alert("Contents are: " + div_selected.html());
}

I made you a small example here...

Upvotes: 1

Related Questions