My javascript:
var countrygroup = [
"AFG-Afghanistan",
"ALA-Åland Islands",
"ALB-Albania",
"DZA-Algeria",
"ASM-American Samoa",
"AND-Andorra",
"AGO-Angola",
"AIA-Anguilla",
"ATA-Antarctica",
"ATG-Antigua and Barbuda",
"ARG-Argentina",
"ARM-Armenia",
"ABW-Aruba",
"AUS-Australia"
];
$(function() {
$.each( countrygroup, function( i, a ){
var sep = a.split('-');
$("#country").append('<option value="' + sep[0] + '">' + sep[1] +'</option>');
});
});
php:
<form action="validation.php" method="post">
<table width="250" align="center">
<tr>
<td>UserId:</td>
<td><input type="text" name="userId" required></td>
</tr>
<tr>
<td>Country Code:</td>
<td><span class="input">
<select name="country" id="country" style="width:100%; white-space:nowrap">
<option value="NIL">Country</option>
<!-- Use jquery to populate options -->
</select>
</span>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd" required></td>
</tr>
<tr align="left">
<td> </td>
<td> <input type="submit" value="Login"></td>
</tr>
</table>
</form>
<script src="js/dropdown_script.js" type="text/javascript"></script>
I want to populate the country list into my dropdown list name country. However all it show was the word "country" in the dropdownlist. What's wrong with my codes? The other time i use the same codes seem to be working but not this. Did i miss out something?
You need to load the jQuery library. Preferably at the bottom (because of efficiency loading reasons), just before loading your javascript (which should NOT be in the head as someone suggested).
It is working in jsfiddle. You should put the script in the head
section of the page:
<script src="js/dropdown_script.js" type="text/javascript"></script>
Also, please note that there is recommended to use absolute paths in order to avoid getting 404 errors: /js/dropdown_script.js
instead of js/dropdown_script.js
As Amarnasan has commented, please make sure you include the jQuery library right before the dropdown_script.js