Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
Selección dinámica de menú desplegable de país, estado y ciudad

Tengo 1 selección desplegable estática (país) y 2 dinámicas (estado y ciudad).

Estoy trabajando con Select2.

Por ejemplo, Holanda tiene una gran cantidad de ciudades para cada estado. Cargar esto es difícil de trabajar.

En mi página de usuario si tengo el siguiente JS:

 $(".state").change(function() { var id=$(this).val(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "../../get/get_city.php", data: dataString, cache: false, success: function(html) { $(".city").html(html); } }); });

get_city.php está funcionando y se parece a:

 if($_POST['id']) { $id=$_POST['id']; $stmtc = $admin_home->runQuery("SELECT * FROM city WHERE state_id=:id"); $stmtc->execute(array(':id' => $id)); ?><option selected="selected">Selecteer een woonplaats:</option><?php while($rowc=$stmtc->fetch(PDO::FETCH_ASSOC)) { ?> <option value="<?php echo $rowc['city_id']; ?>"><?php echo $rowc['city_zip']; ?> <?php echo $rowc['city_name']; ?></option> <?php } }

También probé ya con el AJAX de select2 por separado con este código (también está funcionando):

 $('.itemName').select2({ placeholder: 'Select an item', ajax: { url: '../../get/get_city_ajax.php', dataType: 'json', delay: 250, processResults: function (data) { return { results: data }; }, cache: true } });

get_city_ajax.php se parece a:

 $stmtc = $admin_home->runQuery("SELECT * FROM city " . "WHERE city_name LIKE '%".$_GET['q']."%' LIMIT 10"); $stmtc->execute(); $json = []; while($rowc=$stmtc->fetch(PDO::FETCH_ASSOC)) { $json[] = ['id'=>$rowc['city_id'], 'text'=>$rowc['city_name']]; } echo json_encode($json);

Ahora se necesita una combinación de los dos para obtener solo las ciudades del estado seleccionado.

Intenté mucho pero no pude hacerlo funcionar.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Esta solución funciona bien para mí:

 $(".state").change(function() { var id=$(this).val(); var dataString = 'id='+ id; $('.city').select2({ placeholder: 'Selecteer een stad', ajax: { url: '../../get/get_city_ajax.php?'+dataString, dataType: 'json', delay: 250, processResults: function (data) { return { results: data }; }, cache: true } }); });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!