2016-06-11 78 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> 
相關問題