Onchange event not working when placed on body [closed]

-2

I wrote this function to validate some form-specific radio buttons. As my page is in PHP and I include top and footer includes, the function works when it is in footer.php, but since the function does not apply to all pages, I have to place it individually in the body of the specific pages. When I do this it mysteriously does not work and does not report errors on the console.

$(function(){

    $('body').on( 'change', ':radio', function(){
        if( $('input[value="3"]:checked').length > 5 ){
             alert('Somente 5 opções críticas podem ser marcadas');
            $(this).prop({ checked : false });
        }
    });

});
    
asked by anonymous 28.02.2014 / 14:24

2 answers

1

The problem here seems to be that HTML does not have what the selector was looking for.

When you use:

 $('input[value="3"]:checked')

You are saying to find elements of type input whose value in the attribute value is equal to 3 and whose status is checked .

As you can see in this example , the code works. On the other hand, you can use from this example to find out if your code is actually being used in your environment but without finding results with the selector you applied.

By your comment:

  

@Zuul I discovered that this was it, the value of the form was different, as the form is super great, it was difficult to look for all inputs, it was value "a | 3", now I have here. - Leandro Ruel

We know that your selector searched for value="3" and the HTML had value="a|3" , thus making this question "Too localized" because it is a typo that will hardly help anyone in the future

    
28.02.2014 / 14:59
0

Hello,

Have you put your scripts inside some load checking function?

From what you said, it only works when you put it in the footer after the page loads.

Try with document.ready, so it checks to see if every DOM was loaded before applying the function.

$(document).ready(function(){

    $('body').on( 'change', ':radio', function(){
        if( $('input[value="3"]:checked').length > 5 ){
             alert('Somente 5 opções críticas podem ser marcadas');
             $(this).prop({ checked : false });
        }
    });

});
    
28.02.2014 / 15:09