On(change) event on radio button

Asked

Viewed 5,544 times

1

In the project I have a file that makes inquiries of freight prices and that at the same time returns two radio Buttons with the freight values. The return of the HTML is as follows:

<p>
    <b>Selecione: </b><br>
    <input type="radio" name="tipocep" value="1;40.50" class="seltipocep">
    PAC <b>R$ 40,50</b> prazo de 28 dia(s)<br> <br>
    <input type="radio" name="tipocep" value="2;129.40" class="seltipocep">
    SEDEX <b>R$129,40</b> prazo de 4 dia(s)
    <input type="hidden" name="addfrete" value="1"></p>

This HTML content is returned via the following AJAX request:

$("form#consultafrete").submit(function(event) {
    /* Act on the event */
    event.preventDefault();

    <?php if($pagina == 'carrinho'){ ?>
    var tipoCEP = 100;
    <?php }else{ ?>
    var tipoCEP = '';
    <?php } ?>

    var totalItens = <?php echo $_SESSION['carrinho']['total_itens'] ?>;
    var $legendacep = $("#legendacep");
    var meucepCalc = $("#seucep").val();

    if(meucepCalc != ''){

        $legendacep.html("Carregando...");

        $.post(
            '<?=$siteUrl?>/calcula-frete.php',
            { meucep: meucepCalc, tipo_saida: tipoCEP, qtd: totalItens },
            function(data) {
                var resultado = '<p>'+data+'</p>';                      
                $legendacep.html(resultado);                        
            });
        }
    });

What I intend to do is that when the return has radio Buttons, when selecting one of them, I can do some action, I’ve tried several ways but it doesn’t work. The fact that it doesn’t work is because the content is dynamic? One of the ways I tried:

$("input[name=tipocep]").change(function() {                
                alert("sDSDS");
            });

1 answer

2


Yes the problem is delegation because this content was added after the JS has been read.

You can delegate the event to a relative, for example: #legendacep.

$("#legendacep").on('change', "input[name=tipocep]", function() {                
    alert("sDSDS");
});

Example: http://jsfiddle.net/0xdtg3gx/

  • Perfect @Sergio, working right. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.