0

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);
});
BenMorel
  • 34,448
  • 50
  • 182
  • 322

3 Answers3

3
$(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()

daryl
  • 14,307
  • 21
  • 67
  • 92
0

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?

Community
  • 1
  • 1
Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
  • i mean to ask is if i decalere the value to golbal , im not getting the change value when in funtion onlick –  Jan 05 '12 at 09:27
0

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())})
Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186
  • not exaclty i mean to ask is on click funtion the values change na i have to use in outside that funtion which is dnamic –  Jan 05 '12 at 09:30
  • I'm still not sure what you mean ... please try to rephrase your question ;) – Shlomi Schwartz Jan 05 '12 at 10:05