NitroMuse NitroMuse - 5 months ago 8
jQuery Question

How to return the text from an asp button by clicking on it?

I can return the backgroundColor from this function but not the text or innerText. I have about 100 buttons of which I want to pick both the background color and text when clicked on. I don't want a function for each button.

var c
shows in the alert so I know the alert is working but
var iT
is blank.

I've tried it with both Chrome v51~ and IE11.

$(document).ready(function(){
$(this).click(function () {
var b = document.getElementById(document.activeElement.id);
var c = b.style.backgroundColor;
var iT = b.innerText;
alert(c + " " + iT);
});
});

Answer

Simply:

$(document).ready(function(){
  $('.my-button').click(function () {
    var btn = $(this)
    var color = btn.css('backgroundColor')
    var text = btn.text() || btn.val() // if text is inner html tag, or on value attribute
    alert(color + " " + text);
  });
})

With a link

<a class="my-button">Click me</a> 

With button

<button class="my-button" value="Click me"/>
<input type="submit" class="my-button" value="Submit"/>