submit form from a select

Asked

Viewed 5,992 times

1

I have a <select> with several options, when selecting an option, I want the form to be submitted to the same page and I will fetch the value by php on the same page. For that, I have the following:

<?php
    if(isset($_POST['select_carros']))
    {
         echo $_POST['select_carros'];
    }
?>

<form action="" method="post" name="menuForm">
     <select name="select_carros">
          <option value="1">Carro 1</option>
          <option value="2">Carro 2</option>
          <option value="3">Carro 3</option>
     </select>
</form>

Basically, what I want is that when choosing the option is printed the value of this option. For example, I choose the option "Car 2" and will be printed "2"

3 answers

2

Just use the onChange :

<form action="" method="post" name="menuForm" onchange="this.form.submit();">

1


Complete Example with Last Choice Selection:

<form action="" method="post" name="menuForm">
     <select name="select_carros" onchange="document.forms['menuForm'].submit();">
         <option value="0">Escolha a Opção</option>
          <option value="1" <?php echo isset($_POST['select_carros']) && $_POST['select_carros']==1?' selected="selected"':'';?>>Carro 1</option>
          <option value="2" <?php echo isset($_POST['select_carros']) && $_POST['select_carros']==2?' selected="selected"':'';?>>Carro 2</option>
          <option value="3" <?php echo isset($_POST['select_carros']) && $_POST['select_carros']==3?' selected="selected"':'';?>>Carro 3</option>
     </select>
</form>


<?php
    if(isset($_POST['select_carros']))
    {
         echo $_POST['select_carros'];
    }
?>

0

The action of your form must be submitted to the same page, so you can get the value "2" in the $_POST['select_cars'].

<form action="mesma_pagina.php" method="post" name="menuForm">
  • yes, but it is already being submitted to the same page.

  • 1

    Then use onChange="this.form.Submit();" in the <form>.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.