是否可以在一个html表单中包含许多选择标记?

时间:2016-06-11 09:49:37

标签: javascript php html forms

我想创建一个包含两个不同下拉列表供选择的表单(例如,用于选择名称的下拉列表和用于选择年龄的下拉列表)。然后我想在表格下打印它们。然后我必须能够再次选择其他选项,它们将在第一个选项的打印后打印。

这可能吗?

 <form id="form" action="" method="post">
        <select id="name">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>                
        </select>
        <select id="age">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>                
        </select>
        <input type="submit" value="submit">
</form>

以及如何将所选值传递给php?

1 个答案:

答案 0 :(得分:0)

<body>
    <form id='form'>
        <select id='name' name='selectName'>
            <option value='1'>1</option>
            <option value='2'>2</option>
            <option value='3'>3</option>
            <option value='4'>4</option>
        </select>
        <select id='age' name='selectAge'>
            <option value='1'>1</option>
            <option value='2'>2</option>
            <option value='3'>3</option>
            <option value='4'>4</option>
        </select>
        <input type='submit' value='submit'>
    </form>
    <div id='print'></div> <!-- Here you will print the submitted values -->
</body>
</html>

<!-- ES6 syntax -->
<script>

    const form = document.getElementById('form');
    const print = document.getElementById('print');

    form.addEventListener('submit', function(event) {
        event.preventDefault(); // prevent page reload

        const name = this.querySelector('#name').value; // get the name
        const age = this.querySelector('#age').value; // get the age

        print.innerHTML += `<div>Name: ${name}, Age: ${age}</div>`; // print name and age below the form

        // here you can perform an AJAX call to your PHP file and do something with it

    });

</script>

在这种情况下,没有理由将action='YOUR_PHP_FILE.php'放在表单中,因为您希望将页面和打印的消息保留在下面,所以只需在后台执行AJAX调用。通常你会这样做:

<form id='form' action='YOUR_PHP_FILE.php' method='POST'>
    // ...
</form>

php文件中,您可以执行以下操作:

<?php
    $name = $_POST['selectName'];
    $age = $_POST['selectAge'];

    // do something with these values ...

?>

这是旧的Javascript版本:

<!-- Old syntax -->
<script>

    var form = document.getElementById('form');
    var print = document.getElementById('print');

    form.addEventListener('submit', function(event) {
        event.preventDefault(); // prevent page reload

        var name = this.querySelector('#name').value; // get the name
        var age = this.querySelector('#age').value; // get the age

        print.innerHTML += '<div>Name: ' + name + ', Age: ' + age + '</div>'; // print name and age below the form

        // here you can perform an AJAX call to your PHP file and something with it

    });

</script>