Reputation: 260
I want to create a select box dropdown. initially select box will not have any option, it should show only select. On click of select box it will iterate list and add each option to that select box.
I am trying below code -
$(".droptest").click(function(e){
e.preventDefault();
var listDrop = [{"chdk74":"hdk73","hiphdk":"hiphdk","hpghdk":"hpghdk","ihdk":"ihdk","sdg74":"sdg74"}];
var dropDownlist = JSON.parse(listDrop);
var options = "";
$.each(dropDownlist, function(key,value) {
options += "<option name=" + value +" id=" + value +" value="+value+"> "+ value +" </option>";
});
$(".DomainDrop").html(options);
});
<div class="droptest">
<select class="DomainDrop tet" id="DomainDropCreate" name="DomainDrop" required>
<option name="" value="">Select Domain</option>
</select>
</div>
Upvotes: 0
Views: 37
Reputation: 27041
What you would do is to remove the []
from listDrop
, and then use $.each(listDrop, function(key, value) {
Demo
$(".droptest").mousedown(function(e) {
var listDrop = {
"chdk74": "hdk73",
"hiphdk": "hiphdk",
"hpghdk": "hpghdk",
"ihdk": "ihdk",
"sdg74": "sdg74",
};
var options = "";
$.each(listDrop, function(key, value) {
options += "<option name=" + value + " id=" + value + " value=" + value + "> " + value + " </option>";
});
if ($(".DomainDrop option").length < 2) {
$(".DomainDrop").html(options);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="droptest">
<select class="DomainDrop tet" id="DomainDropCreate" name="DomainDrop" required>
<option name="" value="">Select Domain</option>
</select>
</div>
As Freedomn-m says, change click
to mousedown
and remove e.PreventDefault()
then I all works just fine.
Upvotes: 2