簡體   English   中英

將數據輸入和下拉選擇組合到js中

[英]Combination of data entry and drop down selections into a js

我的頁面上有一個數據輸入部分,用戶必須在其中輸入自己的名字,然后在是/否下拉選項之間進行選擇。 填寫完畢后,用戶單擊“生成”,所有信息,問題和答案將顯示在下面。如何管理js將開放式和下拉式問題/答案都考慮到結果中?如何調整字體大小?結果?這是我到目前為止的結果..

<form name="myForm">
Name: <input type="text" name="firstname">
    <font size="3">
        <label for="q7">- Done it?</label>
    </font>
    <select id="q7">
        <option>Yes</option>
        <option>No</option>
    </select>
    <input type="button" onclick="populateResults()" value="Generate">
        <div id="result"></div>
    </form>
    <script>
function populateResults() {
  var selects = document.forms.myForm.querySelectorAll('select'),
      result = document.getElementById("result");
  Array.from(selects).forEach(function(a, i) {
      var answer = a.options[a.selectedIndex].text,
          question = selects[i].labels[0].textContent;
      result.innerHTML += question + ' ' + answer + '
            <br>';
  })
}

        </script>
    </body>
</html>

首先,對於option中的選項,它應該具有value屬性。

您正在使代碼過於復雜。

您可以這樣做:

<form name="myForm">
Name: <input type="text" name="firstname" id="firstname">
<font size="3">
    <label for="q7">- Done it?</label>
</font>
<select id="q7">
    <option value="yes">Yes</option>
    <option value="no">No</option>
</select>
<input type="button" onclick="populateResults()" value="Generate">
    <div id="result"></div>
</form>

<script src="jquery.js"></script>
<script>
function populateResults() {
    var select = $('#q7').val();
    var name = $('#firstname').val();
    var result = name + ' - Done it? ' + select;
    $('#result').text(result);
}

    </script>

這很冗長,但是在這里我添加了一些ID,從標記中刪除了代碼,在標簽中添加了一個類,因此我倆都可以找到它的樣式:

修改后的標記:

<form id="myform" name="myForm">Name:
    <input type="text" name="firstname" id="firstname" />
    <label for="q7" class="mylabel">- Done it?</label>
    <select id="q7">
        <option value="yes">Yes</option>
        <option value="no">No</option>
    </select>
    <input type="button" value="Generate" id="generate" />
    <div id="result"></div>
</form>

添加此CSS(刪除了過時的字體標簽)

.mylabel {
    font-size:1.5em;
}

VERBOSE代碼(將其清理干凈,使意圖很明顯)

function populateResults() {
    var myselect = $('#q7');
    var selectedText = myselect.find('option:selected').text();
    var selectedVal = myselect.val();
    var question = myselect[0].labels[0].textContent;//same thing
    question = myselect.siblings('.mylabel').text();// same thing
    $('#result').append(question + ' :' + selectedText + ":" + selectedVal + '<br />');
}
$('#myform').on('click', '#generate', populateResults);

暫無
暫無

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

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