How to use AJAX to populate state list depending o

2020-02-01 06:08发布

问题:

I have the code below that will change a state dropdown list when you change the country list.
How can I make it change the state list ONLY when country ID number 234 and 224 are selected?
If another country is selected it should be change into this text input box

<input type="text" name="othstate" value="" class="textBox">

The form

<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>

<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>

The javascript

<script>
function getState(countryId)
{
   var strURL="findState.php?country="+countryId;
   var req = getXMLHTTP();
   if (req)
   {
     req.onreadystatechange = function()
     {
      if (req.readyState == 4)
      {
     // only if "OK"
     if (req.status == 200)
         {
        document.getElementById('statediv').innerHTML=req.responseText;
     } else {
       alert("There was a problem while using XMLHTTP:\n" + req.statusText);
     }
       }
      }
   req.open("GET", strURL, true);
   req.send(null);
   }
}
</script>

回答1:

Just check the countryId value before you do the AJAX request and only perform the request if the countryId is in the allowable range. In the case where the countryId doesn't match, I would hide the select (probably clear it's value, too) and show an already existing input that was previously hidden. The reverse should be done if an allowable country is chosen.

jQuery example below:

<form method="post" name="form1">
   <select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
      <option>Select Country</option>
      <option value="223">USA</option>
      <option value="224">Canada</option>
      <option value="225">England</option>
      <option value="226">Ireland</option>
   </select>

   <select style="background-color: #ffffa0" name="state">
      <option>Select Country First</option>
   </select>

   <input type="text" name="othstate" value="" class="textBox" style="display: none;">
</form>

$(function() {
    $('#country').change( function() {
        var val = $(this).val();
        if (val == 223 || val == 224) {
            $('#othstate').val('').hide();
            $.ajax({
               url: 'findState.php',
               dataType: 'html',
               data: { country : val },
               success: function(data) {
                   $('#state').html( data );
               }
            });
        }
        else {
           $('#state').val('').hide();
           $('#othstate').show();
        }
    });
});


回答2:

I think the simple thing to do is to provide a state dropdown and a text entry box with different ids. Set the display of both to none and then you just need to surround your contents of getState() with

if (countryId == 233 || countryId == 234) {
   /* Ajax state population here */

   dropdownId.display = 'block';
   textEntryId.display = 'none';
}
else  {
   textEntryId.display = 'block';
   dropdownId.display = 'none';
}

(where dropdownId and textEntryId are the ids of the relevant UI components) so you enable/display the display for the state dropdown or the text entry upon selection.

JQuery is all well and good, but I wouldn't introduce it just to solve this problem.



回答3:

EDIT: here is a solution that works quite well for the task, adapting the lines of Tvanfosson:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>

<script>
$(function() {
  $('#country').change( function() {
    var val = $(this).val();
    if (val == 223 || val == 224) {
        $('#othstate').val('').hide();
        $.ajax({
           url: 'findState.php',
           dataType: 'html',
           data: { country : val },
           success: function(data) {
               $('#state').html( data );
           }
        });
    }
    else {
       $('#state').val('').hide();
       $('#othstate').show();
    }
  });
});
</script>

<select style="background-color: #ffffa0" name="country" id=country >
  <option>Select Country</option>
  <option value="223">USA</option>
  <option value="224">Canada</option>
  <option value="225">England</option>
  <option value="226">Ireland</option>
</select>

<select style="background-color: #ffffa0" name="state">
  <option>Select Country First</option>
</select>

<input type="text" name="othstate" id=othstate value="" class="textBox" style="display: none;">

As you can see, I eliminated the <form> element which is not absolutely necessary but can be added (and then has to be used properly in case JS is deactivated at the users end. See here.

I also eliminated the onchange event which is being replaced by the 'change()` jquery function.



回答4:

VK API just select country , get it id and select city from

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
    
var $j = jQuery.noConflict();
var _getCountry = function() {
    $j.ajax({
      url: "http://api.vk.com/method/database.getCountries",
      data: {
       'v': 5.5,
        'need_all': 0,
        'code' : 'RU,UA,BY,KZ,KG,LV,EE'  
       // 'count': 10
      },
      dataType: 'jsonp',
      success: function(data, status) {
        if (status !== 'success') {
          return false;
        }
        console.log(data.response, status); 
          
        $j.each(data.response.items, function(i, item) {
         console.log("each country");
         var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
         country_options.push(newOption);
       });
    
       document.getElementById('countrylist').innerHTML = country_options;
          
      }
        
 });  
 }   

var _getCity = function(country_id) {
     
    $j.ajax({
      url: "http://api.vk.com/method/database.getCities",
      data: {
       'v': 5.61,
        'need_all': 0,
        'country_id': country_id
      },
      dataType: 'jsonp',
      success: function(data, status) {
        if (status !== 'success') {
          return false;
        }
        console.log(data.response, status); 
          
        $j.each(data.response.items, function(i, item) {
         console.log("each city");
         var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
         city_options.push(newOption);
       });
    
       document.getElementById('citylist').innerHTML = city_options;
          
      }
        
 });  
 }  
       
var  city_options = [];
var  country_options = [];
    
 $j(document).ready(function () {  
    _getCountry(); 
     
  $j('#country').on('input',function() {
    var opt = $j('option[value="'+$j(this).val()+'"]');
    var countryid = opt.attr('id');  
      
    _getCity(countryid);  
      
     
  });

  
 });

</script>
 <div class="form-group">
          <label class="col-lg-4 control-label">Страна:</label>
          <div class="col-lg-8">
          
              <div class="controls">
            	<input name="country" list="countrylist" id="country" class="form-control" />
                <datalist id="countrylist">
                </datalist> 
              </div>
        
           
           
            
          </div>
        </div> 
   
        <div class="form-group">
          <label class="col-lg-4 control-label">Город:</label>
          <div class="col-lg-8">
                
            <input name="city" list="citylist" id="city" class="form-control"/>
                <datalist id="citylist">
            </datalist>  
              
           
          </div>
        </div> 



回答5:

////////////////// connection file con.php rishabh
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = '';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);
         if(! $conn ) {
            die('Could not connect: ' . mysql_error());
         }
         mysql_select_db( 'testajax' );
?>

/////////////////////////// index.php rishabh
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<?php 
include('con.php');
?>
<form>
<div class="frmDronpDown">
    <div class="row">
        <table><tr><td><label>Country:</label><br/>
        <select name="country" id="country" data-name="country" class="demoInputBox" onChange="getCountry(this.value);">
        <option value="">Select Country</option>
        <?php
         $sql = mysql_query("SELECT distinct country FROM statecont ");
     while($result=mysql_fetch_array($sql)){
        ?>
        <option value="<?php echo $result['country']; ?>"><?php echo $result['country']; ?></option>
        <?php
        }
        ?>
        </select> </td>
             <td>
<label>Phone:</label><br/>
        <select name="phone" id="phone" data-name="phone" class="demoInputBox" onChange="getPhone(this.value);">
        <option value="">Select Country</option>
        <?php
         $sql = mysql_query("SELECT distinct phone FROM statecont ");
     while($result=mysql_fetch_array($sql)){
        ?>
        <option value="<?php echo $result['phone']; ?>"><?php echo $result['phone']; ?></option>
        <?php
        }
        ?>
        </select> 
</td></tr></table>
    </div>
    <div id="state-list"></div>
</div>
</form>
<script>
function getCountry(val) {
        var dataname = $('#country').attr('data-name');

        console.log(dataname);
    $.ajax({
    type: "POST",
    url: "data.php",
        data: {
                value_name: val,
                colomn_name: dataname
                },
    success: function (data){
        $("#state-list").html(data);
    }
    });
}

function getPhone(val) {
        var dataname = $('#phone').attr('data-name');

    console.log(dataname);
    $.ajax({
    type: "POST",
    url: "data.php",
        data: {
                 value_name: val,
                colomn_name: dataname
                },
    success: function (data){
        $("#state-list").html(data);
    }
    });
}
</script>

// ////////////////////data file data.php rishabh
<?php 
$val = $_POST["value_name"]; 
$colomn = $_POST["colomn_name"]; 
include('con.php');
$sql_aa = mysql_query("SELECT * FROM statecont where ".$colomn."='$val'"); ?>
  <table>
<tr><td>State</td><td>Countery</td></tr>
<?php while($result_aa=mysql_fetch_array($sql_aa)){ ?>
<tr><td><?php echo $result_aa['state']; ?></td><td><?php echo $result_aa['country']; ?></td></tr>
<?php } ?>
</table>


回答6:

**index.html**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("select.country").change(function(){
        var selectedCountry = $(".country option:selected").val();
        $.ajax({
            type: "POST",
            url: "ajaxServer.jsp",
            data: { country : selectedCountry } 
        }).done(function(data){
            $("#response").html(data);
        });
    });
});
</script>
<style>
select { width: 10em }
</style>
</head>
<body>
<form>
    <table>
        <tr>
            <td> <label>Country:</label></td>
            <td>    <select class="country">
                    <option>Select</option>
                    <option value="usa">United States</option>
                    <option value="india">India</option>
                    <option value="uk">United Kingdom</option>
                </select>
            </td>
        </tr>
        <tr><td >
        <label>States:</label></td>
     <td>   <select id="response">
                    <option>Select State</option>

                </select>
        </td></tr>

    </table>
</form>
</body> 
</html>

**ajaxServer.jsp**
<option>Select State</option>
<% 
String count=request.getParameter("country");
String india[]={"Mumbai", "New Delhi", "Bangalore"};
String usa[]={"New Yourk", "Los Angeles","California"};
String uk[]={"London", "Manchester", "Liverpool"};
String states[];
if(count.equals("india"))
{
    for(int i=0;i<=2;i++)
    {
    out.print("<option>"+india[i]+"</option>");
    }
}
else if(count.equals("usa"))
{
    for(int i=0;i<usa.length;i++)
    {
    out.print("<option>"+usa[i]+"</option>");
    }
}
else if(count.equals("uk"))
{
    for(int i=0;i<=2;i++)
    {
    out.print("<option>"+uk[i]+"</option>");
    }
}

%>