Retrieve Button value with jQuery

Viewed 272271

A simple one, I'm trying to retrieve the value attribute of a button when its been pressed using jQuery, here's what I have:

<script type="text/javascript">
    $(document).ready(function() {
        $('.my_button').click(function() {
            alert($(this).val());
        });
    });
</script>

<button class="my_button" name="buttonName" value="buttonValue">
    Button Label</button>

In Firefox my alert displays 'buttonValue' which is great but in IE7 it displays 'Button Label'.

What jQuery should I use to always get the button's value? Or should I be using a different approach?

Many thanks.

ANSWER: I'm now using

<input class="my_button" type="image" src="whatever.png" value="buttonValue" />
9 Answers

As a button value is an attribute you need to use the .attr() method in jquery. This should do it

<script type="text/javascript">
    $(document).ready(function() {
        $('.my_button').click(function() {
            alert($(this).attr("value"));
        });
    });
</script>

You can also use attr to set attributes, more info in the docs.

This only works in JQuery 1.6+. See postpostmodern's answer for older versions.

Give the buttons a value attribute and then retrieve the values using this:

$("button").click(function(){
  var value=$(this).attr("value");
});

try this for your button:

<input type="button" class="my_button" name="buttonName" value="buttonValue" />

if you want to get the value attribute (buttonValue) then I'd use:

<script type="text/javascript">
    $(document).ready(function() {
        $('.my_button').click(function() {
            alert($(this).attr('value'));
        });
    });
</script>
Related