Finding a class item in a button group in jQuery

Currently, I am trying to make two buttons in the same way as 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 we return 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 does not work and will not return a button with an active class. I also tried to use hasClass('active'), but I can’t figure out how to get this to find the active button with it.

+4
source share
4 answers

Your code seems to work as it is, see here

If this does not work 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');

.text(), , , , .

+1

.text() .val().

+3

You need to set the value purchaseTypeat the right time and 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>
Run codeHide result
0
source

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

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

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

Source: https://habr.com/ru/post/1625416/


All Articles