【发布时间】:2021-06-07 10:49:30
【问题描述】:
我有一个简单的表单,用户可以在其中提交拨号代码和电话号码!在数据库中添加新实例时,它工作正常。但是,我在编辑现有实例时遇到了一些问题。在数据库中,我将dialcode 保存为integer,将phone number 保存为integer(例如213 将存储阿尔及利亚的拨号代码和1234567890 电话号码)
我设法解决了这个问题,但仍然有问题!这按预期工作,但我将不得不重新加载页面以使其执行。下面的代码如何实现一次且仅一次,并且当页面加载时与其余数据(姓名、电子邮件、twitter、电话号码)类似?
换句话说,如何在下拉菜单中设置选定的选项,因为我知道值是什么。
<script type="text/javascript">
//select tag
let country_code = document.getElementById("country_code_dropdown");
//set correct option according to numeric value:
window.onload = function(){
//get current dial code value:
let dialCode = document.getElementById("country_phone_code_input").value; //357
//Loop through
Array.from(document.querySelector("#country_code_dropdown").options).forEach(function(option_element) {
let option_value = option_element.value;
if(option_value == dialCode){ //if value matches:
option_element.selected = true; //set <option> to selected: true
document.getElementById("phone_number_input").innerHTML = "+" + option_value; //and change span
}
});
};
</script>
【问题讨论】:
标签: javascript html ruby-on-rails html-select option