Selects dependent 2 levels

I need your help : (

I have a problem with dependent dropdowns in 2 levels, one is for country, and the other for City. The problem is that when I click a country, in the dropdown of the city I get stuck inside the entire html page and I can not see where I fail... I hope you can help me...

Here is the Code:

// JavaScript Document
var  conexion = null;

function crearXMLHttpRequest() {
	var xmlhttp=false;
	try{
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(E){
			if (!xmlhttp && typeof XMLHttpRequest!='undefined') xmlhttp=new XMLHttpRequest();
		}
	}
	return xmlhttp; 
}

//declaramos los dropdowns del documento HTML
var listadoSelects = new Array();
listadoSelects[0] = "pais";
listadoSelects[1] = "ciudad";

/*funcion que devuelve la posicion donde esta el elemento dentro del array*/
function buscar(array, valor){
	var i = 0;
	
	while(array[i]){
		if(array[i] == valor){
			return i;
			i++;
		}
	}
	
	return null;
}

function cargarContenido(idOrigen){
	//cojemos la posicion que ocupa el dropdown que tiene que ser puesto en el array
	var posicionDestino = buscar(listadoSelects,idOrigen)+1;		
	//obtenemos el dropdown que el usuario ha modificado
	var origen = document.getElementById(idOrigen);
	//obtenemos la opcion seleccionada
	var seleccionada = origen.options[origen.selectedIndex].value;
	
	//si el usuario eligio la opcion Elige.. no buscaremos nada en la BBDD
	if(seleccionada == ""){
		var x = posicionDestino;
		var actual = null;
		
		//deshabilitamos las opciones de el select dependiente ya que no hemos seleccionado ningun valor
		while(listadoSelects[x]){
			actual = document.getElementById(listadoSelects[x]);
			actual.length = 0;
			
			var nuevaOpcion = document.createElement("option");
			nuevaOpcion.value = 0;
			nuevaOpcion.innerHTML = "Selecciona una opción..";
			actual.appendChild(nuevaOpcion);
			actual.disabled = true;
			x++;
		}
		
	}else if(idOrigen != listadoSelects[listadoSelects.length-1]){
		var idDestino = listadoSelects[posicionDestino];
		var destino = document.getElementById(idDestino);
		
		var ajax = crearXMLHttpRequest();
		ajax.open("GET","action.php?action=dependientes&select="+idDestino+"&option="+seleccionada, true);
		ajax.onreadystatechange = function(){
				if(ajax.readyState == 1){
					destino.length = 0;
					var nuevaOp = document.createElement("option");
					nuevaOp.value = 0;
					nuevaOp.innerHTML = "Cargando...";
					destino.appendChild(nuevaOp);
					destino.disabled = true;
					
				}if(ajax.readyState == 4){
					destino.parentNode.innerHTML = ajax.responseText;
				}
			
		}
		
		ajax.send(null);
	}
	
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" lang="es-es">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link href="css/bootstrap.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="font-awesome-4.5.0/css/font-awesome.min.css"/>
		<link href="css/css.css" rel="stylesheet" type="text/css" media="all" />
		<link rel="stylesheet" type="text/css" href="css/icSquared_v1.0.css"/>
		<title>Información del usuario</title>
	</head>
<body>
<div>
	<div class="registro">
		<div class="container-fluid">
			<div class="col-xs-12 col-sm-12 col-md-2" style="left:79%; margin-top:2%">
				<?php echo $msgReg; ?>
				<form action="action.php?accion=userRegisterInfo" method="post" role="form" enctype="multipart/form-data">
					<h3 class="text-center" style="font-size:35px"> Datos Personales </h3><br />
					<div class="form-group">
						<label>Que eres?</label>
						<?php desplegable_tipoUser(-1); ?>
					</div>
					<div class="form-group">
						<label>Nombre</label>
						<input type="text" name="nombre" class="form-control" required="required" placeholder="Introduce tu nombre"/>
					</div>
					<div class="form-group">
						<label>Apellidos</label>
						<input type="text" name="apellidos" class="form-control" required="required" placeholder="Introduce tus apellidos"/>
					</div>
					<div class="form-group">
						<label>Fecha de nacimiento</label>
						<input type="date" name="fechaNac" required="required" />
					</div>
					<div class="form-group">
						<label>Sexo:</label><br />
						<input type="radio" name="sexo" value="male" checked="checked"/> <i class="fa fa-mars fa-lg"></i> Hombre &nbsp;&nbsp;&nbsp;&nbsp;
						<input type="radio" name="sexo" value="female" /> <i class="fa fa-venus fa-lg"></i> Mujer 
					</div>
					<div class="form-group">
						<label>Pais:</label>
						<?php desplegable_pais(); ?>
					</div>
					<div class="form-group">
						<label>Población:</label>
						<select disabled="disabled" name="ciudad" id="ciudad">
							<option value="0">Selecciona una opción..</option>
						</select>
					</div>	
					<div class="form-group">
						<label>Imagen de Perfil:</label>
						<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
						<input type="file" enctype="multipart/form-data" name="foto_perfil" required="required">
					</div>			
					<br/>
					<input class="btn btn-success" type="submit" id="enviar" value="Guardar" style="margin-left:40%"/>
				</form>
			</div>
		</div>
	</div>

</div>
<script src="js/jquery-1.12.1.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/selectsDependientes.js"></script>
</body>
</html>

And here the php code bunch:

<?php
//connect BD function
function conectar(){
    $connect = mysqli_connect("localhost","root","xxxx","xxxx");

    //set the language
    $connect->query("SET NAMES 'utf8'");

    return $connect;
}

//disconect BD function
function desconectar($connect){
    mysqli_close($connect);
}


    //dropdown pais 
function desplegable_pais(){ 
$conexion = conectar(); $sql = "SELECT * FROM PAIS";

    echo '<select name="pais" id="pais" onChange="get_ciudad(this.value);">';
    echo '<option value="0">Elige un País</option>';
    if($resultado=$conexion->query($sql)){
        while($fila=mysqli_fetch_array($resultado)){
            echo '<option value="'.$fila[0].'">'.$fila[1].'</option>';
        }
    }else{
        echo '<p> Error en la conexion o consulta.. </p> <br />';
    }

    echo '</select>';
    desconectar($conexion);
}




<?php 
if($action == "dependientes"){
    $listadoSelects=array(
    "pais"=>"lista_pais",
    "ciudad"=>"lista_ciudad"
    );

    $destino = $_GET['select'];
    $seleccionado = $_GET['option'];

    //funcion que valida que el select enviado por GET exista
    function validar($destino){
        global $listadoSelects;
        $validado = false;

        if(!isset($listadoSelects[$destino])){
            $validado = true;
        }

        return $validado;
    }

    //funcion que valida la opcion seleccionada
    function validarOp($seleccionado){
        $validado = false;

        if(is_numeric($seleccionado)){
            $validado = true;
        }

        return $validado;
    }

    if(validar($destino) && validarOp($seleccionado)){
        $conexion = conectar();

        $sql = "SELECT idPoblacion, nombre,comunidadAut FROM POBLACION WHERE id_pais='".$seleccionado."'";

        if($resultado = $conexion -> query($sql)){
            echo '<select name="'.$destino.'" id="'.$destino.'" onChange="cargarContenido(this.id)">';
            echo '<option value="0">Elige</option>';
            while($fila = mysqli_fetch_array($resultado)){
                //$fila[0] = htmlentities($fila[0]);

                echo "<option value='".$fila[0]."'>".$fila[1]." - ".$fila[2]."<option>";
            }
        }
    }
 2
Author: Jordi Castilla, 2016-03-30

2 answers

There is a bug in the line showing cities:

         echo "<option value='".$fila[0]."'>".$fila[1]." - ".$fila[2]."<option>";

You never close the <option> tag if not you open a new one, and that's why you see everything pasted. The solution is simple, close the tag <option>:

         echo "<option value='".$fila[0]."'>".$fila[1]." - ".$fila[2]."</option>";
 1
Author: Alvaro Montoro, 2016-03-30 12:31:16

This is the simplest or simplest thing I can offer you...

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">

<FORM>
    <SELECT id="departamento" name="departamento"> 
        <OPTION value=0 selected>Elija departamento</OPTION>
        <OPTION value=1>BOACO</OPTION>
        <OPTION value=2>CARAZO</OPTION>
        <OPTION value=3>CHINANDEGA</OPTION>
</SELECT> 
<br />

<select id="municipio" disabled>
    <OPTION value=0 selected>Elija municipio</OPTION> 
</select> 

<script> 
    $(document).ready(function () {
        $("#departamento").change(function () {
            $("#municipio").prop('disabled', false);
            if (this.value == 1) {
                $("#municipio").html("<OPTION value=9>boaco</OPTION><OPTION value=59>teustepe</OPTION>");
            }
            else if (this.value == 2) {
                $("#municipio").html("<OPTION value=01>jinotepe</OPTION><OPTION value=41>diriamba</OPTION>");
            }
            else if (this.value == 3) {
                $("#municipio").html("<OPTION value=69>chinandolfi</OPTION><OPTION value=19>corintio</OPTION>");
            }
            else {
                $("#municipio").prop('disabled', true);
                $("#municipio").html("<OPTION value=0 selected>Elija municipio</OPTION>");
            }
        });
    });
</script>
 0
Author: Nestrix, 2018-01-23 08:22:32