簡體   English   中英

單擊具有指定功能的按鈕時,如何在輸出框中的下拉列表中顯示選項的值?

[英]How do I display the value of an option on a drop down in an output box when a button with an assigned function is clicked on?

單擊具有指定功能的按鈕時,如何在輸出框中的下拉列表中顯示選項的值? 我是編程新手,不太了解。

/* This function is meant to take the value of the selected option and 
  display it in the output textbox */
function scoringValue() {
  var chosenOne = document.getElementById("totalPoints").value + document.getElementById("options").value;
  document.getElementById("totalPoints").value = chosenOne;
}

我對在下面分配值感到困惑

<p>
  Scoring:
  <select id="options">
    <option value="3">1</option>
    <option value="2">2</option>
    <option value="7">3</option>
    <option value="6">4</option>
    <option value="8">5</option>
  </select>
  <input type="button" id="findScore" value="Score" onclick="return scoringValue()" />
  Total Points: <input type="text" id="totalPoints" value=0 disabled="disabled" class="output" />

您需要在代碼中parseInt值,因為它們以字符串形式存在。 因此,如果您將兩個字符串“ 2” +“ 2”相加,則結果將為“ 22”。 因此答案是:使用parseInt將字符串轉換為數字以正確地求和。 這是一個例子:

 function scoringValue() { var chosenOne = parseInt(document.getElementById("totalPoints").value, 10) + parseInt(document.getElementById("options").value, 10); document.getElementById("totalPoints").value = chosenOne; } 
 <p>Scoring:<select id="options"> <option value="3">3</option> <option value="2">2</option> <option value="7">7</option> <option value="6">6</option> <option value="8">8</option> </select> <input type="button" id="findScore" value="Score" onclick="scoringValue()" /> Total Points: <input type="text" id="totalPoints" value=0 disabled="disabled" class="output" /> 

您可以使用parseInt將值從字符串轉換為int,然后執行計算。

例:

function scoringValue() {
    var totalPoints = parseInt(document.getElementById("totalPoints").value, 10);
    var optionsValue = parseInt(document.getElementById("options").value, 10);
    var chosenOne =  totalPoints + optionsValue;
    document.getElementById("totalPoints").value = chosenOne;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM