Tab
Tab

Reputation: 309

How to get value of a button type button with jQuery?

I use instead of I simply wish to get the value/content of the selected/active button, with jQuery, on click button and onload page.

These are my buttons:

<button type="button" class="green test">Button 1</button>
<button type="button" class="green active test">Button 2</button>

I know I must to use $(".test:button") selector, but I don't know how to get the button content

Upvotes: 2

Views: 7167

Answers (4)

Anton
Anton

Reputation: 32581

Use .text()

$(document).ready(function(){

    alert($('.test[type="button"]').text());

    $('.test[type="button"]').on('click',function(){
         alert($(this).text());
    });

});

DEMO

Edit

var text = $('button.active').text();

Edit

var redsText = $('button.red.active').text();
var greensText = $('button.green.active').text();

Upvotes: 3

Ramki
Ramki

Reputation: 166

<head> 
<script type="text/JavaScript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<button type="button" class="green test">Button 1</button>
<button type="button" class="green active test">Button2</button>
<script>
$(function(){
$(".green").click(function(){
$(this).addClass('active');

    $(this).siblings().removeClass("active")
alert($(this).text());
})
 })
</script>

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Try

 $('button.test').click(function() {
        alert($(this).text());
    });

WORKING DEMO

Upvotes: 1

Subdigger
Subdigger

Reputation: 2193

$('button').text();

or

$('button').html();

Upvotes: 1

Related Questions