How to make a scroll on the same page when selecting a Radio Button option?

1

I need that when a radio button is selected, lower the screen automatically. I have this HTML code:

<label><input type="radio"  name="radio" value="1"  id="boton1"  class="ancla" data-ancla="scroll"  /></label>
<label><input type="radio" name="radio" value="2" id="boton2"  class="ancla" data-ancla="scroll" /></label>

and this JavaScript code:

$('.ancla').on('click', function(e){
e.preventDefault();
var strAncla = '#' + $(this).data('ancla');
$('html,body').animate({scrollTop: $(strAncla).offset().top}, 1500);
});

But when clicking, it does what I want but it does not select any radio button that I will use later to save it in the database.

How do I solve it? Thanks!

    
asked by Diego Lopez 17.11.2017 в 23:06
source

2 answers

1

That happens because by doing the e.preventDefault(); you are canceling the default behavior of the radio button , then you must force the attribute checked of the element to be selected using the function prop() of jQuery , as follows:

$('.ancla').on('click', function(e){
        e.preventDefault();
    
        var elemento = $(this);
    
        var strAncla = '#' + $(this).data('ancla');
        $('html, body').animate({
            scrollTop: $(strAncla).offset().top
        }, 1500, function(){ 
            $(elemento).prop("checked", true); 
        });
    });
#scroll{
  height: 200vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<label><input type="radio"  name="radio" value="1"  id="boton1"  class="ancla" data-ancla="scroll"  /></label>
<label><input type="radio" name="radio" value="2" id="boton2"  class="ancla" data-ancla="scroll" /></label>

<div id="scroll"></div>
    
answered by 17.11.2017 / 23:19
source
1

Try this.

There must be a separation between the two to appreciate the displacement.

To test the snippet, activate the Página completa option that appears on the right.

$("#boton1").click(function() {

  $('html, body').animate({
    scrollTop: $("#boton2").offset().top
  }, 1500);
  $("#boton2").prop("checked", true);

});
.espacio {
  margin-top: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="radio"  name="radio" value="1"  id="boton1"  class="ancla" data-ancla="scroll"  /></label>
<div class="espacio"></div>
<label><input type="radio" name="radio" value="2" id="boton2"  class="ancla" data-ancla="scroll" /></label>
    
answered by 17.11.2017 в 23:33