首页 > 解决方案 > 动态改变输入属性的值

问题描述

嗨,我需要根据选择的下拉列表动态更改输入属性的 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>

标签: javascripthtml

解决方案


由于您已经在下拉更改事件上定义了一个函数(称为 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();

推荐阅读