Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery event listener for radio buttons

Tags:

jquery

I'm trying to create a jquery event listener for a set of settings. This is a sample of the radio buttons:

<div class="settings">
    <input type="radio" id="a1" name="a" value="1" style="display: none;" />
        <label for="a1">a1</label>
    <input type="radio" id="a2" name="a" value="2" style="display: none;" />
        <label for="a2">a1</label>
    <input type="radio" id="a3" name="a" value="3" style="display: none;" />
        <label for="a3">a1</label>
</div>
<div class="settings">
    <input type="radio" id="b1" name="b" value="1" style="display: none;" />
        <label for="b1">a1</label>
    <input type="radio" id="b2" name="b" value="2" style="display: none;" />
        <label for="b2">a1</label>
    <input type="radio" id="b3" name="b" value="3" style="display: none;" />
        <label for="b3">a1</label>
</div>

I need a jquery listener for when a radio button is clicked, but I'm getting confused because the radio buttons aren't clicked, they're hidden. It's the labels that are clicked. I also need to know which button is clicked. This is far as I've gotten:

$('.settings label').click(function() {
    alert("Something was clicked"); // test - not working
    // need something to determine what was clicked
    updateSettings('a', 'value'); // what was checked, and the value, stored to database via separate function
});

But this doesn't work, and I don't know how to tell WHAT was clicked (a1, a2.. b2, etc.)

like image 370
user2250471 Avatar asked Jun 13 '14 18:06

user2250471


2 Answers

Change it to this:

$('.settings label').click(function() {
  console.log('Value of Radion: '.concat($(this).prev().val(), 'Name of radio: ', $(this).prev().attr('name')));
});
input[type=radio] {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="settings">
  <input type="radio" id="a1" name="a1" value="1" />
  <label for="a1">a1</label>
  <input type="radio" id="a2" name="a2" value="2" />
  <label for="a2">a1</label>
  <input type="radio" id="a3" name="a3" value="3" />
  <label for="a3">a1</label>
</div>
<div class="settings">
  <input type="radio" id="b1" name="b1" value="1" />
  <label for="b1">a1</label>
  <input type="radio" id="b2" name="b2" value="2" />
  <label for="b2">a1</label>
  <input type="radio" id="b3" name="b3" value="3" />
  <label for="b3">a1</label>
</div>
like image 119
Alex Char Avatar answered Nov 07 '22 17:11

Alex Char


Demo Fiddle

Use Query .attr()

Try this,

$(function(){
    $('.settings label').click(function() {

          updateSettings($(this).attr('for'), $('#'+$(this).attr('for')).val());
    });
});
like image 23
Shaunak D Avatar answered Nov 07 '22 18:11

Shaunak D