0

I have a link element as below, the value of this link element is set dynamically (Asynchronously).

The value of the label will be null until its set by an ajax call asynchronously.

<a href="#"  onclick="myFuncton(**I want to pass the label element value - testClass**);"><label class="testClass"></label></a>

I want to pass the value of the label to a JavaScript function.

 <script>
  function myFunction(label value){
  alert(label value);
  }
  </script>

I am trying to figure out the best way to achieve this. Can someone help me with any suggestions / ideas?

Learner
  • 2,303
  • 9
  • 46
  • 81

3 Answers3

2

I would recommend using jQuery event handlers...

Having said that, this in the context of onclick will refer the the anchor element so

function myFuncton(value) {
  alert(value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" onclick="myFuncton($(this).find('label.testClass').text());">
  <label class="testClass">ddd</label>
</a>

Using jQuery event handlers

jQuery(function($) {
  $('.myanchor').click(function(e) {
    e.preventDefault();
    var label = $(this).find('.testClass').text();
    alert(label)
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="myanchor">
  <label class="testClass">some text</label>
</a>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Use this html first

onclick="printLabel()"

Then JS

function myFunction(label){
        alert(label);
}

function printLabel(){
        myFunction($('.testClass').text());
}

Using JS code inside onclick attribute is a really bad practice, this attribute should only be used to call function

Ahmad
  • 477
  • 2
  • 9
  • It is never too late to lead by example with code maintainability and good practices: http://stackoverflow.com/questions/6941483/onclick-vs-event-handler – Sukima Oct 07 '14 at 03:03
0

I think parameter is not required for function. You can get the value using 'this' attribute. You can try one of the following:

Using pure JavaScript:

this.children[0].innerText;

Using JQuery:

$('.testClass', this).text();