zoruc
zoruc

Reputation: 819

Finding a class element in a group of buttons in JQuery

I'm currently trying to make two buttons behave in a similar fashion to radio buttons, where only one can be selected at a time.

HTML

<button class="button" value="purchase" name="selector_button_group">
      Purchase
</button>
<button class="button" value="refinance" name="selector_button_group">
      Refinance
</button>

jQuery

$("button[name=selector_button_group]").click(function() {
  $("button[name=selector_button_group]").removeClass('active');
  $(this).addClass('active');
});

Now getting back the value of the selected button

var purchaseType =  $("button[name=selector_button_group].active").val();

or

var purchaseType =  $("button[name=selector_button_group]").hasClass('active').val();

However this doesn't work and will not return the button with the class active. I have also tried using hasClass('active') but I cannot figure out how to get this to find the active button with it.

Upvotes: 4

Views: 90

Answers (4)

Leonardo
Leonardo

Reputation: 314

You can use the jQuery siblings() function, so:

$("button[name=selector_button_group]").click(function() {
    $(this)
        .addClass('active')
        .siblings('.button')
        .removeClass('active');

    var val = $("button[name=selector_button_group].active").text();
});

Upvotes: 0

Pabs123
Pabs123

Reputation: 3435

Your code seems to be working as is, see it here

If that is not working and you want to keep the same code structure as you currently have try changing:

$("button[name=selector_button_group].active").val();

To:

$("button[name=selector_button_group].active").attr('value');

You could also use .text() as previously suggested, but this solution will allow you to change the value so that it is not the same as the text if you so wish.

Upvotes: 1

colecmc
colecmc

Reputation: 3318

You have to set value of purchaseType at the right time and to the exact thing you want.

var purchaseType;

$("button[name=selector_button_group]").click(function() {
  $("button[name=selector_button_group]").removeClass('active');
  $(this).addClass('active');
  purchaseType = $(this).text();
  console.log(purchaseType);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Finding a class element in a group of buttons in JQuery</title>
</head>
<body>

  <button class="button" value="purchase" name="selector_button_group">
      Purchase
</button>
<button class="button" value="refinance" name="selector_button_group">
      Refinance
</button>
  
  
</body>
</html>

Upvotes: 0

Cameron
Cameron

Reputation: 434

Try using .text() instead of .val().

Upvotes: 3

Related Questions