没有选择javascript onchange赋予价值

时间:2015-09-21 16:19:08

标签: javascript

onchange未被选中或者nochange给出值如何? 看看我的例子

<select id="leave" onchange="leaveChange()">
  <option value="500">Worldwide</option>
  <option value="150">EMS</option>
  <option value="350">DHL</option>
  <option value="200">UPS</option>
  <option value="75">Postal</option>
</select>
<input type="button" name="button" id="button" value="+Add" />
<script>
function leaveChange() {
        var leaveValue = document.getElementById("leave").value;
        var shippingItems = document.getElementById("item_ship");
            if (leaveValue != ' ') // ??
                shippingItems.innerHTML = leaveValue;
            else
                shippingItems.innerHTML = this.value;
}
</script>
<div id="item_ship"></div>

我认为我的问题很明确。如果打开页面给定的值为<option value="500">Worldwide</option>,则值500如何获取div id

1 个答案:

答案 0 :(得分:0)

如果您希望将Worldwide选为自动选项,只需将其添加到您的HTML中:

<option value="500" selected>Worldwide</option>

要在页面加载时将item_ship的值设置为全球选定值,您可以尝试以下操作:

<强> HTML

<select id="leave" onchange="leaveChange()">
  <option value="500" selected>Worldwide</option>
  <option value="150">EMS</option>
  <option value="350">DHL</option>
  <option value="200">UPS</option>
  <option value="75">Postal</option>
</select>

<强>的Javascript

<script>

 function setItemShip() {
    var leaveValue = document.getElementById("leave");
    var itemShip = document.getElementById("item_ship");
    // sets the value of #item_ship to selected value
    itemShip.innerHTML = leaveValue.options[leaveValue.selectedIndex].value;
 }

  window.onload = setItemShip;

</script>

这是一个实时代码示例 - EXAMPLE