Javascript和HTML-从SPAN和选择中获取价值

时间:2018-10-19 15:45:27

标签: javascript html

我对Javascript编程还很陌生。我想从呈现给客户的值列表中获取选定的值。我想将其显示为一个简单的文字,说的是从提供的选项中进行选择。让我粘贴代码段

<span id="Step2" style="display:none">
<form>
   <fieldset>
      <legend>Type of Customization</legend>
      <p>
         <label>Available Customization</label>
         <select id = "myCust">
           <option value = "1">New Dimension Table</option>
           <option value = "2">Add a Fact Table</option>
           <option value = "3">Completely New Form</option>
           <option value = "4">Edit an Old Form</option>
           <option value = "5">Others</option>
         </select>
      </p>
   </fieldset>
</form>

所以从提供的选项中,如果该人选择说“完全新的表单”,我想将其显示在HTML中

我尝试过

document.getElementById("myCust")

但是那行不通。

1 个答案:

答案 0 :(得分:1)

function getCust() {
    var typeofCust = document.getElementById("myCust");
    var cust = typeofCust.querySelector('option[value="'+typeofCust.value+'"]');

    document.getElementById('selected-customer').innerText=cust.innerText;
}

document.getElementById('myCust')
  .addEventListener('change', getCust)
<div id="FooterTableStep2" style="background-color:Silver">
    Selected Customization : <span id="selected-customer"></span>
</div>

<form>
    <fieldset>
        <legend>Type of Customization</legend>
        <p>
            <label>Available Customization</label>
            <select id="myCust">
                <option value="1">New Dimension Table</option>
                <option value="2">Add a Fact Table</option>
                <option value="3">Completely New Form</option>
                <option value="4">Edit an Old Form</option>
                <option value="5">Others</option>
            </select>
        </p>
    </fieldset>
</form>

getElementById返回实际的HTML element object

const selectEl = document.getElementById('myCust');
const customer = selectEl.value;
console.log(customer); // selected value

值得注意的是,大多数元素也可以查询其子级

const row = document.querySelector('td:nth-child(13)');
const selectEl = row.getElementById('some-id');

已更新为包含您的评论:

<td id="FooterTableStep2" style="background-color: silver;">
    Selected Customization: <span id="selected-customer"></span>
</td>

<script>
    function getCust() {
        var typeofCust = document.getElementById("myCust");
        var cust = typeofCust.querySelector('option[value="' + typeofCust.value + '"]');

        document.getElementById('selected-customer').innerText = cust.innerText;
    }
</script>