user887563
user887563

Reputation:

How to get the click event values outside the function in jQuery

How can I get the onclick event (this value change when click on div) in jQuery?

$("ul li").click(function(){
  var v = $(this).val();
});

$(function(){
  alert(v);
});

Upvotes: 0

Views: 4262

Answers (3)

Hemant Metalia
Hemant Metalia

Reputation: 30638

as I understand that you want to change the text of a div

your div is as follow

 <div>123</div>

you can do it as

<script>

$("div").click(function () {
 $(this).replaceWith( "new text " );
});
</script>

EDIT you can use global variable as follow

 $.mynamespace = {};
$("ul li").click(function(){
       $.mynamespace.myVar  = $(this).val();
});

$(function(){
  alert( $.mynamespace.myVar );
});

refer How to store a global value (not necessarily a global variable) in jQuery?

Upvotes: 0

daryl
daryl

Reputation: 15197

$(function() {

    var v;

    $('ul li').click(function() {
        v = $(this).val(); // .text() - consider
        testFunction();
    });

    function testFunction() {
        alert(v);
    }

});

Your issue was variable scope, you were defining a variable only available to the click function. If you define it outside of the function it will be available to other in scope functions.

Here's a demo:

http://jsfiddle.net/vs87B/

You might want to consider using .text() instead of .val()

Upvotes: 3

Shlomi Schwartz
Shlomi Schwartz

Reputation: 8903

If what you mean getting the innerHTML of the div when clicked, here is a code that could help

$("div").click(function(){console.log($(this).html())})

Upvotes: 0

Related Questions