更改下拉菜单的“选定值”

时间:2018-12-05 08:16:26

标签: javascript

我有“产品类别”下拉列表,这是我显示的关于产品的项目之一。

Product Category:
<label class="ff" for="f"><em>*</em></label>
<div class="sort-options-wrapper" id="f" >
    <select class="sort-options" id="sortOptions" 
    onchange="SelectedValueF(this)">
    </select>
</div>

在准备好文档时加载下拉列表,并且所选项目默认为列表中的第一个商品猫。然后,我从数据库中加载产品记录,其中包含一个产品猫。我想在下拉菜单中将“选择的项目”设置为从数据库记录中检索到的项目。我已经尝试了许多在stackoverflow存档中找到的建议,但对我没有任何帮助。另外,我使用了一些新的JavaScript,J Query,Ajax等,但是我正在尝试。

2 个答案:

答案 0 :(得分:0)

嵌套的 <body> <div id = "images"> <img id="image1"> </div> </body> $.ajax({ url: "/api/v1/get-all-upload-image?sortBy=date", type: "GET", success: function(response){ console.log(response); $.ajax({ url : "/api/v1/base-strings", type:"GET", success:function(response){ console.log(response.response.data) for (i= 0; i < response.response.data.length; i++){ console.log(response.response.data[i]) var base64_string = response.response.data[0].base_string; var img = document.createElement("img"); // added `width` , `height` properties to `img` attributes img.width = "250px"; img.height = "250px"; img.src = "data:image/jpeg;base64," + base64_string; var preview = document.getElementById("images"); preview.appendChild(img); } } }); } }); 标签应具有与选择选项相同的属性“值”。然后,您只需<option>

以下示例演示了随机选项的选择

$('#sortOptions').val(optionValue)
$(document).ready(()=>{
  let options = ['a','b','c','d'];
  $('#optionSelect').val(options[Math.floor(Math.random()*(options.length))]);
})

答案 1 :(得分:0)

您可以设置:

document.getElementById("sortOptions").value = "your_value";

(onchange)=this.value

function SelectedValueF(val)
{
  console.log(val);
  document.getElementById("sortOptions").value = "C";
}
Product Category:
<label class="ff" for="f"><em>*</em></label>
<div class="sort-options-wrapper" id="f" >
    <select class="sort-options" id="sortOptions" 
    onchange="SelectedValueF(this.value)">
    <option>A</option>
    <option>B</option>
    <option>C</option>
    </select>
</div>

相关问题