nicker nicker - 3 months ago 8
Javascript Question

Jquery how to use $(this) to get value of clicked item?

I have trouble getting value of particular item that I'd clicked

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(this).click(function(){
alert($(this).find("button").html());
});
});
</script>
</head>
<body>
<p>test 1</p>
<p>test 2</p>
<button>Yes</button>
<button>No</button>
</body>
</html>



  • I'd tried
    $(this).find("button").html()
    , but it will return the value of 1st button("Yes) even if I clicked the 2nd button("No")

  • Same for
    $(this).find("p").html()
    , will return value of 1st

  • How do I use
    $(this)
    to get the value of item I clicked?

  • Don't suggest me to insert class or id, I'm not suppose to touch the html.

  • Please assist, thanks.


Answer

It is because $(this).click event listener is added to document object and not any specific html element.

$(document).ready(function(){
    $('button,p').on('click',function(){
        alert($(this).html());
    });
});

plunker: https://jsfiddle.net/wx38rz5L/1743/