如何在 html 元素中打印选项值?

How to print option value in html element?

我正在尝试添加一个 h2 元素,该元素根据所选的选项值显示和更新价格。

这是我当前的代码:

<select name="price">
  <option value="2799"> 1-6 תשלומים</option>
  <option value="3200">12 תשלומים </option>
  <option value="2799"> 36 תשלומים</option>
</select>

我们可以通过添加 onchange 事件来打印选项值。

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    </head>
    <body>
        <select name="price" onchange="changePrice()">
            <option value="2600"> 1-6 תשלומים</option>
            <option value="3200">12 תשלומים </option>
            <option value="2799"> 36 תשלומים</option>
        </select>
        <h2 id="id"></h2>
        <script>
            function changePrice() {
                var selector = document.getElementsByName("price")[0];
                var value = selector[selector.selectedIndex].value;
                document.getElementById('id').innerHTML = value;
            }
            document.addEventListener("DOMContentLoaded", changePrice);
        </script>
    </body>
    </html>