Save Value of an Input Radio in a Javascript variable

0

This code corresponds to the JavaScript code:

<script type="text/javascript">
$(document).ready(function() {
    var Id = document.getElementsByName("rama");//ESTA ES LA FORMA QUE USO
    let activoFijo = $('input[name="activoFijo"]:checked').val();//ESTA LA ENCONTRE COMO RESPUESTA A OTRA PREGUNTA SIMILAR A ESTA
    $.post("../Sql/ArregloPersonas.php", {Id: Id
        }, function(){
            $("#personas-rama").html();
    });
});
</script>

The second part of the code contains the radio type input:

<div class="container">
    <div class="row">
    <div class="col-3">
        <input type="radio" name="rama" value="1"> Manada
    </div>
    <div class="col-3">
        <input type="radio" name="rama" value="2"> Tropa
    </div>
    <div class="col-3">
        <input type="radio" name="rama" value="3"> Comunidad
    </div>
    <div class="col-3">
        <input type="radio" name="rama" value="4"> Clan
    </div>
    </div>
</div>

I want that when the person selects a radio input its value is stored in a variable of JS and an alert is shown that shows the selected value; and if the radio input is changed, an alert must also appear with the new selected value.

Thanks in advance for the help for this problem.

    
asked by Danyel Melendez Ramirez 18.10.2018 в 06:52
source

1 answer

2

First, tell you that you are mixing in your Javascript statements made with pure Javascript, with sentences made with Jquery. It is not a good practice and it can take you to make a real mess.

Here is a function that will help you achieve the desired effect:

var valor = '';

$("input[name='rama']" ).on('change', function () {
    valor = $(this).val();
    alert(valor);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="row">
    <div class="col-3">
        <input type="radio" name="rama" value="1"> Manada
    </div>
    <div class="col-3">
        <input type="radio" name="rama" value="2"> Tropa
    </div>
    <div class="col-3">
        <input type="radio" name="rama" value="3"> Comunidad
    </div>
    <div class="col-3">
        <input type="radio" name="rama" value="4"> Clan
    </div>
    </div>
</div>

What I do is add a change event (this event triggers when input changes value) to all input with the name "branch". Then I save the value in a variable that I have initialized outside the function and I do a alert .

    
answered by 18.10.2018 / 09:39
source