如何将json值附加到选择列表

时间:2018-03-10 07:04:30

标签: javascript jquery html

[{"key":"0.75","value":"3/4","Default_Value":"0"}, 
 {"key":"0.875","value":"7/8","Default_Value":"1"},
"key":"1.75","value":"1 3/4","Default_Value":"0"}]

我有json数组如何追加这个json有选择列表的选项

这是我想要追加的方式

<option value="0.75">3/4</option>
<option value="0.875">7/8</option>
<option value="1.75">1 3/4</option>

我需要选择默认值,如果&#34; Default_Value&#34;:&#34; 1&#34;我没有得到如何迭代和获取值以及在选项中显示关键值的痛苦,并且非常感谢任何帮助。

&#13;
&#13;
$("#p_combination").empty();
//supposing that your response object is something like :
var response=[{'dish_name':'3/4','dis-val':0.75},{'dish_name':'7/8','dis-val':0.875},{'dish_name':'1.75','dis-val':1.75}];
for(var i = 0; i < response.length; i++) {
 $("#p_combination").append("<option value='" + response[i]['dis-val'] + "'>" +response[i]['dish_name'] + "</option>");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<select name="p_combination[]" id="p_combination" multiple>
    <option value="0">Select</option>
</select>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

 $arrays=json_decode([{"key":"0.75","value":"3/4","Default_Value":"0"}, 
 {"key":"0.875","value":"7/8","Default_Value":"1"},
"key":"1.75","value":"1 3/4","Default_Value":"0"}]);
foreach($arrays as $array){
$select="";
if($array->Default_Value==1){
$select="selected='selected'";
}
echo '<option '.$select.' value="'.$array->value.'">'.$array->value.'</option>';
}

答案 1 :(得分:0)

您的json格式错误。你错过了{。我会使用selected属性来设置选中的内容。除此之外,我刚刚创建了一个for循环来创建每个选项并将其添加到select

var jData = [{"key":"0.75","value":"3/4","Default_Value":"0"}, 
 {"key":"0.875","value":"7/8","Default_Value":"1"},
 {"key":"1.75","value":"1 3/4","Default_Value":"0"}];

for (var i = 0, len = jData.length; i < len; i++) {
  var isSelected = jData[i].Default_Value == "1" ? 'selected="selected"' : "";
  $("select#buildSelect").append("<option " + isSelected + " value='" + jData[i].key + "'>" + jData[i].value + "</option>")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="buildSelect"></select>

答案 2 :(得分:0)

&#13;
&#13;
// Values.
const values = [
  {value:"0.75", text:"3/4"}, 
  {value:"0.875", text:"7/8", isDefault: true},
  {value:"1.75", text:"1 3/4"}
]

// Select.
const select = $('#select')

// Append children using forEach + template literal.
values.forEach(({value, text, isDefault}) => select.append(`<option value=${value} ${isDefault && 'selected=true'}>${text}</option>`))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select"></select>
&#13;
&#13;
&#13;