在HTML表单中添加下拉选项

Add a Drop Down Option in an HTML form

本文关键字:选项 添加 HTML 表单      更新时间:2024-07-20

我是否可以在我的两个表格上添加一个下拉选项,如性别(男性或女性选项)和验证(如果是或否),然后当我点击提交时,它会显示我输入的那个?

    <form id="myForm">
        Phone: <br><input type="text" name="Phone Number" placeholder="Phone Number"/><br/>
        Gender: <br><input type="text" name="Gender" placeholder="Gender"/><br/>
        INBOUND: <br><input type="text" name="INBOUND" placeholder="INBOUND"/><br/>
        Name: <br><input type="text" name="Name" placeholder="Name"/><br/>
        Status: <br><input type="text" name="Status" placeholder="Status" /><br/>    
    <button type="button" onclick="ShowText();">Submit</button>
    </form>
    <p>Result:</p>
    <p><textarea cols=40 rows=8 id="show" onClick='selectText(this);'></textarea></p>
    
    <script>
    function ShowText(){
        // find each input field inside the 'myForm' form:
        var inputs = myForm.getElementsByTagName('input');
        // declare 'box' variable (textarea element):
        var box = document.getElementById('show');
        // clear the 'box':
        box.value = '';
        // loop through the input elements:
        for(var i=0; i<inputs.length; i++){
            // append 'name' and 'value' to the 'box':
            box.value += inputs[i].name + ': '+inputs[i].value+''n';
        }
    }M
    function selectText(textField) 
      {
        textField.focus();
        textField.select();
      }
    </script>
    
    <textarea rows="8" cols="40">
    Issue:
    
    
    Steps:
    </textarea>

在表单中,您应该使用select而不是输入

<select name="Gender" placeholder="Gender"><option>Male<option>Female</select>

接下来,您可以使用querySelectorAll 获取input标记和select标记

var inputs = myForm.querySelectorAll('input,select');

综合起来:

<form id="myForm">
        Gender:<select name="Gender" placeholder="Gender"><option>Male<option>Female</select><br/>
        Name:<input type="text" name="Name" placeholder="Name"/><br/>
    <button type="button" onclick="ShowText();">Submit</button>
    </form>
    <p>Result:</p>
    <p><textarea cols=40 rows=8 id="show" onClick='selectText(this);'></textarea></p>
    
    <script>
    function ShowText(){
        // find each input field inside the 'myForm' form:
        var inputs = myForm.querySelectorAll('input,select');
        // declare 'box' variable (textarea element):
        var box = document.getElementById('show');
        // clear the 'box':
        box.value = '';
        // loop through the input elements:
        for(var i=0; i<inputs.length; i++){
            // append 'name' and 'value' to the 'box':
            box.value += inputs[i].name + ': '+inputs[i].value+''n';
        }
    }
    function selectText(textField) {
        textField.focus();
        textField.select();
    }
    </script>