Skip to content
Advertisement

How to get the button text through calling a method

I am working on this demo. Why am I not getting the text of the #add-point button?

$("#add-point").on("click", function(){
  activatePointTool();
});

function activatePointTool() {
  var tool = $(this).text().toUpperCase().replace(/ /g, "_");
  console.log(tool);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add-point" class="btn btn-default btn-tool">Point</button>

Advertisement

Answer

You don’t have any “this” in your function. You either need to pass it to your function or execute your code in the on click function. The this is a really important feature to master when coding in JS.

Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

$("#add-point").on("click", function(){
  activatePointTool(this);
});

function activatePointTool(el) {
  var tool = $(el).text().toUpperCase().replace(/ /g, "_");
  console.log(tool);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add-point" class="btn btn-default btn-tool">Point</button>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement