Ali Ben Messaoud
Ali Ben Messaoud

Reputation: 11920

Dynamic select box to populate a textfield using AJAX or jQuery and PHP

Is there any tutorial or code that help to poulate a textfield from a chosen value from a select box usuig AJAX or jQuery and PHP? Like in the picture ...

enter image description here

Upvotes: 1

Views: 3990

Answers (2)

Noki Flores
Noki Flores

Reputation: 257

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
  //Please visit http://www.nokiflores.com
$(document).ready(function () {
   $("#country").change(
       function () {
           $("#capital").val($(this).val());
       }
   );
});
</script>
<select id="country" name="country">
  <option value="Delhi" >India</option>
  <option value="manila" >phil</option>
  <option value="tokyo" >japan</option>
</select>

<input type="text" readonly="readonly" value="" id="capital" name="capital" />

try this one: if you want to use php you will do it another way using ajax. Please visit http://www.nokiflores.com

Upvotes: 6

Vinayak Garg
Vinayak Garg

Reputation: 6616

I guess once you fill Delhi, the script can decide India, not opposite. However if you want to make a subset of cities available, for selected country: that makes sense.

To your question, for this you would need a mammoth list of all major countries and there cities.

My approach: In javascript make a array of 'country'. Make a csv list for each country (like in.csv, us.csv etc.)

Now using JS populate country option fields. Once country is selected, fire Jquery to fetch corresponding 'country-code.csv' using ajax. Then Simply make a selection list of fetched city-names.

Note: Some people would object on CSV, choose any file format you find appropriate.

Upvotes: 0

Related Questions