javascript - 动态改变输入属性的值
问题描述
嗨,我需要根据选择的下拉列表动态更改输入属性的 value 属性中的硬编码 url。
以下是我尝试但无法正常工作的代码。我是 Javascript 新手。请帮忙
var returnValue = checkDropDown();
var myValue = returnValue === "DropDown1" ? "http://url1/..." : "http://url2..";
var input = document.getElementById('URLField');
input.value = myValue;
function checkDropDown() {
const platForm = $('#platform-select').val();
console.log("platform select"+platForm);
return platForm;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<label for="platform">Choose from dropdown :</label>
<select name="platform" id="platform-select" onchange="togglePlatformOptions()">
<option value="DropDown1" >foo</option>
<option value="DropDown2" selected>bar</option>
</select>
<input type="text" id="URLField" value="myValue"/>
</body>
解决方案
由于您已经在下拉更改事件上定义了一个函数(称为 togglePlatformOptions),因此您可以使用它。只需将您的功能添加到此功能即可。像下面
function togglePlatformOptions(){
//you old code if it exists already
var returnValue = document.getElementById('platform-select').value;
var myValue = returnValue === "DropDown1" ? "http://url1/..." : "http://url2..";
var input = document.getElementById('URLField');
input.value = myValue;
}
更新:似乎你有一个函数 checkDropDown,然后添加你里面的所有东西
function togglePlatformOptions(){
var returnValue = checkDropDown();
var myValue = returnValue === "DropDown1" ? "http://url1/..." : "http://url2..";
var input = document.getElementById('URLField');
input.value = myValue;
}
更新#2:要在初始化时调用它
function togglePlatformOptions(){
var returnValue = checkDropDown();
var myValue = returnValue === "DropDown1" ? "http://url1/..." : "http://url2..";
var input = document.getElementById('URLField');
input.value = myValue;
}
// below call added
togglePlatformOptions();
推荐阅读
- huawei-developers - 应用启动:Huawei Lite Simulator 仅支持 Lite 项目
- python - 在张量流中对数组进行过采样和下采样
- javascript - 通过锚链接偏移浏览器原生平滑滚动
- godot - Godot图像缩放不同
- sqlite - 向 sqlite db golang 提交哈希时出错
- python - 获取熊猫系列中先前出现的值的索引
- android - “GooglePlayServicesNotAvailableException”与 robolectric:4.6.1
- postgresql - postgres 中的 Schemaname 和 tableowner
- python - 强制更改/识别 VS Code-Python 中笔记本文件的编码以运行另一个 jupyter 笔记本文件
- algorithm - 证明对 TREE-SUCCESSOR 的 k 次连续调用需要 O(k + h) 时间