how to use $ (this) + checked?

3
<input type="radio" name="teste1" value="SIM"> TESTE 1
<input type="radio" name="teste1" value="NÃO"> TESTE 2



$(document).ready(function(){
    $("[name='teste1']").click(function () {
        var teste = $(this+":checked").val();
        alert(teste);

    });
});    

How to get the value using $ (this) + checked?

    if($("[name='teste1']").is(":checked")){
        var teste = $(this+":checked").val();
        alert(teste);
    }

is giving error: link

I would like to know how to use the :checked selector, when this is already the selector.

    
asked by anonymous 28.10.2015 / 16:00

2 answers

5

There is also another way, which is to use the filter function.

So:

 $(function (){
      
      $("[name='teste1']").click(function () {
         alert($(this).filter(':checked').val());
      });
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputtype="radio" name="teste1" value="SIM"> TESTE 1
<input type="radio" name="teste1" value="NÃO"> TESTE 2

The first case may fit very well, but you can still do it using the change function, since this is the current element in which the event was triggered.

Use the change function:

 $(function (){

      $("[name='teste1']").change(function () {
         alert($(this).val());
      });
    })

Note: With change, it will only fire when there is a change between values. That is, clicking on an already checked checkbox, there will be no activities captured by change .

    
28.10.2015 / 16:08
4

Try this:

$(this).is(":checked")

Something I also like to do, particularly, is to assign everything in variables, like this:

var $myRadio = $("#idDoRadio");

$myRadio.on('click', function () {
    if ($(this).is(":checked")) {
          alert($(this).val())
    }
});
    
28.10.2015 / 16:02