How to auto fill select box in html using jquery & ajax

Here is my HTML (which I think is where the problem is):

<form name="County" method= "post" action="post">
<select id= item.county_name name= item.county_name> 
<option value="item.county_name"> County </option>

</select>
</form> 

      

Here is my javascript:

$.ajax({
url:'http://107.170.75.124/courts/courts.json',
method: 'post'
})
.done (function(data){
   data.forEach(function(item){
    console.log (item.county_name);
     $ ('select'). append ('<option value="' + item.county_name + '">' + 
'</option>');


})
}); 

      

When I try to run it, the dropdown shows all 100 areas where they should be county, but they are empty. So my guess is that there is something wrong with the HTML so that it is not visible. All counties are displayed on my console.

+3


source to share


2 answers


You forget to specify the actual value displayed elements <option>

. The elements are <option>

completed as follows:

<option value='ajax result item here'></option>

      

If the item is <option>

empty.

Change the line as follows:



 $ ('select').append('<option value="' + 
     item.county_name + '">' + item.county_name + '</option>');

      

Or, just this (because when no value is explicitly set to option

, the value becomes the display text option

):

 $ ('select').append('<option>' + item.county_name + '</option>');

      

+3


source


The parameter "value"

just sets the parameter value, but not the label. The label must be between tags<option>

Your code is incomplete.

$ ('select').append('<option value="' + item.county_name + '">' + '</option>');

      

results in something like this

<option value="somecountry"></option>

      



You need to change it like:

$ ('select').append ('<option value="' + item.county_name + '">' + item.county_name + '</option>');

      

which should output

<option value="somecountry">somecountry</option>

      

0


source







All Articles