简体   繁体   中英

How to send the value of a label upon onclick event

I am trying to send the value of the label upon click of this anchor tag.Can anyone suggest me what is the best way to pass the label value(label value varies dynamically so want to pass that value upon click of the anchor to the java script function.)

Sample code:

<a class="k-link" onclick="Getvalue("$("#ID").html()">Profile</a>

2

function Getvalue(Id) {
}

Not entirely sure what you are trying to get here, but does this work (in your onclick)?

$(this).html();

or

$(this).text();

or better, as chase suggested, use jquery to hook up your events so that you can keep it separate from the html:

$(".k-link").click(function() {
    var label = $(this).text();
    // Do something with the label...
});

use .text() instead of .html() :

jQuery

$("a").on("click", function(){
   alert($(this).text());
})​

EXAMPLE

Because we are binding the click event via jQuery, you don't need to do this inline. Your HTML then becomes:

<a class="k-link">Profile</a>

Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)

That's not really a label, nor an element that has value, it's a regular anchor and if what you want is the text it contains you can do:

$('a.k-link').on('click', function(e) {
    e.preventDefault();
    var txt = $(this).text(); //gets text
    var id = this.id; //gets ID, if you need it ?
});
<label id="lbltest">10</label>
<button type="button" onclick='addToCart(lbltest.innerHTML)'>+</button>

Working good for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM