Does not show by alert the selected item of a select

0

I have a select that I load with the data that I bring from my BD, I have a javascritp function to which I send as a parameter the element of the list that I select, but then in the function I make an alert to show what arrives but it always arrives empty. I do not see anything in the alert.

PHP and HTML code

<select class="custom-select form-control" id="tipo" onchange="cargarCategoria(this)">
    <option selected></option>
    <?php
        require ('conexion/Conexion.php');
        $query = "SELECT DISTINCT tipo FROM formacion";
        $result = mysqli_query($con,$query);
        while($fila = mysqli_fetch_array($result))
        {
           echo '<option value="">'.$fila["tipo"].'</option>';
        }
    ?>
</select>

JavaScript code

function cargarCategoria(dato)
{
    alert(dato.value);//Este es el valor que llega vacio, deberia ser el elemento seleccionado del select.
    $.ajax({
        type: "POST",
        url: 'consultas/consultarCategoria.php',
        data: 'tipo='+dato,
        success: function(resp){
            $('#categoria').html(resp);
        }
    });
}
    
asked by Mario Guiber 22.05.2018 в 17:07
source

3 answers

1

Obviously, the value "value" of this select may not be obtained in this way ... I reply the code you pass in the option. The value is empty, so when accessing that value, I may paint it to you, but since it is empty, you do not see it, or I will put it as undefined because you initialize it with an empty set.

echo '<option value="">'.$fila["tipo"].'</option>'

Try this and reprint, otherwise it works look at this with a "console.log"

echo '<option value=".$fila["tipo"]">'.$fila["tipo"].'</option>'
    
answered by 22.05.2018 / 17:12
source
2

If you use jQuery, because you do not handle it with a .on instead of assigning it the onchange in select

It could be something like that

$('#tipo').on('change',function(){

    alert(
      $(this).val()
    );

    $.ajax({
        type: "POST",
        url: 'consultas/consultarCategoria.php',
        data: 'tipo='+dato,
        success: function(resp){
            $('#categoria').html(resp);
        }
    });

});

This way, the alert would show the val() of your select when changing.

An important issue that I had not noticed, is that in your while you are assigning all your option a value=""

echo '<option value="">'

So effectively, it will always return "" the frontend, because the option has an empty value!

    
answered by 22.05.2018 в 17:14
1

When you click on an element of a select what would arrive by parameter is not what is inside the option tags but what is in its value.

Replace

echo '<option value="">'.$fila["tipo"].'</option>';

By

echo '<option value="'.$fila["tipo"].'">'.$fila["tipo"].'</option>';
    
answered by 22.05.2018 в 17:16