2016-06-11 76 views
0

我想要创建一个表单,该表单有两个不同的下拉列表可供选择(例如,选择名称的下拉列表和选择年龄的下拉列表)。然后我想在表格下打印它们。然后,我必须能够再次选择其他选项,并在拳头选项打印后打印。是否有可能在一个HTML表单中有很多选择标签?

这可能吗?

<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?

+0

1.是的,它是可能的。 2.你需要给你的'访问php代码中的选项的方式? –

+0

是的,当你使用'method =“post”'它是'$ _POST [:]':-) – andlrc

回答

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> 
相关问题