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);
});
5
  • 1
    You are going to need to explain your issue a little better ? what do you want to happen when ? Commented Jan 5, 2012 at 9:16
  • 1
    Maybe give some example code that isn't working, and an explanation of what you want to happen? Commented Jan 5, 2012 at 9:18
  • funtion? I believe you mean function Commented Jan 5, 2012 at 9:29
  • ya that by spell mistake thats function Commented Jan 5, 2012 at 9:32
  • If you simply want access to the event, you can do this: $("ul li").click(function(event){ var clickEvent = event; }); Commented Dec 30, 2013 at 19:37

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

hey i want to use click value in another funtion
You can use v in any other function inside the $(function() {}); call with this code.
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())})

2 Comments

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
I'm still not sure what you mean ... please try to rephrase your question ;)
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?

1 Comment

i mean to ask is if i decalere the value to golbal , im not getting the change value when in funtion onlick

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.