【问题标题】:Jquery 3.3.1 populate Dropdown from JSON objectJquery 3.3.1 从 JSON 对象填充 Dropdown
【发布时间】:2018-09-09 12:54:48
【问题描述】:

尝试运行一个示例以将 JSON 对象解析到下拉列表。使用最新的 jquery-3.3.1.js 和 IE 11。有人可以纠正以下示例吗?

var test = { Cars: [{"CarType": "BMW","carID": "bmw123"},{"CarType": "mercedes","carID": "merc123"}, {"CarType": "volvo","carID": "vol123r"}, {"CarType": "ford", "carID": "ford123"}]};

$(document).ready(function(){           
  var mySelect = $('#reportingQuarter');
    $.each(test.Cars, function(key, value) {   
    mySelect.html($("<option></option>").attr("value",key).text(value)); 
    }); 
 })

<div class="col-md-4 mb-3">
 <label for="reportingQuarter">Reporting Quarter</label>
 <select class="form-control" id="reportingQuarter" required>
 <option value="">Please choose Report Quarter</option>
 </select>
   <div class="invalid-feedback">
   Please select Reporting Quarter.
   </div>
 </div>

错误: 仅显示 [object Object] 的下拉列表

【问题讨论】:

标签: jquery-3


【解决方案1】:

试试这个

$.each(test.Cars,function(key, value) {
  $("#mySelect").append($('<option></option>').val(value.carID).html(value.CarType));
});

【讨论】:

  • 从其他帖子中阅读,建议将 DOM 组件保持在循环之外。这就是原因,我在循环之外为 SelectCombo 声明了一个变量。介意更新代码吗?
  • 感谢您的帮助。
【解决方案2】:

我不想带走您的编码风格,但请认真尝试一下。

 <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var test = { Cars: [{"CarType": "BMW","carID": "bmw123"},{"CarType": "mercedes","carID": "merc123"}, {"CarType": "volvo","carID": "vol123r"}, {"CarType": "ford", "carID": "ford123"}]};

$(document).ready(function(){           
  var mySelect = $('#reportingQuarter');
    $.each(test.Cars, function(key, value) {   
    $("#reportingQuarter").append("<option value="+value.CarType+">"+value.CarType+"</option>"); 
    }); 
 })
</script>
<div class="col-md-4 mb-3">
 <label for="reportingQuarter">Reporting Quarter</label>
 <select class="form-control" id="reportingQuarter" required>
 <option value="">Please choose Report Quarter</option>
 </select>
   <div class="invalid-feedback">
   Please select Reporting Quarter.
   </div>
 </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 2013-06-10
    • 2023-03-21
    • 2017-03-20
    • 2018-11-12
    • 1970-01-01
    相关资源
    最近更新 更多