JavaScript - Activar evento change al llenar un select con ajax y php

 
Vista:
sin imagen de perfil
Val: 35
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

Activar evento change al llenar un select con ajax y php

Publicado por Jonathan (23 intervenciones) el 27/08/2020 07:57:29
Tengo una funcion php que genera un select de la siguiente forma
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php include 'conexion.php';
class ListadoRoles {
 
	public function maquinas(){
		$con = new Conexion();
        $Query = "SELECT rol FROM roles";
        $roles = $con->obtenerdatos($Query);
        $filas = $con->numerofilas2($Query);
        $HTML = '';
        if($filas > 0){
            $HTML .= '<select name="rol" id="rol" class="custom-select custom-select-sm form-control-resp inputs">';
            for($i=0,$filas;$i<$filas;$i++){
                $HTML .= '<option value="'.$roles[$i]['rol'].'">'.$roles[$i]['rol'].'</option>';
            }
            $HTML .= '</select>';
        }else{
            $HTML .='<select name="rol" id="rol" class="custom-select custom-select-sm form-control-resp" disabled></select>';
        }
        return $HTML;
    }
}
$inputs = new ListadoRoles();
if(isset($_POST["action"])){
	$html1 = $inputs->maquinas();
	$data = array(
		"html1" => $html1
	);
	echo json_encode($data);
}
?>

Y con ajax lo cargo asi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function mostrar_registros(CantidadPagina, PaginaNumero){
    var action = 'fetch_data';
    var PaginaNumero = PaginaNumero;
    var CantidadPagina = CantidadPagina;
    var rol = document.getElementById("rol").value;
    $.ajax({
        url:"<?php echo $raiz;?>buscar/buscar_permisos.php",
        method: "POST",
        dataType: "json",
        data:{ action:action,CantidadPagina:CantidadPagina,PaginaNumero:PaginaNumero,rol:rol},
        success:function(data){
            $(document).trigger('change');
            $('.listado_registros').html(data.html1);
        }
    });
}

Con el evento change se ejecuta bien la función , el problema es que al recién cargar la pagina, el evento change a un no se ejecuta, entonces no me muestra los datos hasta seleccionar una opción del select, como podria mostrar los datos al momento de cargar la pagina. Y ya cuando cambie la opción del select vallan cambiando los datos según la opción seleccionada.

1
2
3
$(document).on('change','#rol',function(){
    mostrar_registros();
})
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder