Home > OS >  Get and submit multiple selection buttons values range
Get and submit multiple selection buttons values range

Time:11-09

I'm trying to submit multiple buttons and use them as range selectors.

In page1.php I have $array of years 1980, 1990, 2000, 2010, ... which range is updated by database content:

<form method="post" action="page2.php"> 
   <?php
   foreach ($array as $item) {
   ?>
        <input type="submit" name="<?= $item ?> "  value="<?= $item ?> " />                                                      
   <?php
   }
   ?>
</form>

this way I can't click two buttons one after another to set the range, for example from 2000 to 2010, and submit only after this action.

I've tried JavaScript function with onclick without the post method, which counts clicks and pushes two (first and second) clicks values as range to the resettable $rangeval array before if (count == 2) condition comes true, passing values to second JavaScript function request(input) from page1.php using ajax, requesting page2.php with if (isset($_POST['val1']) && isset($_POST['val2'])) and echo json_encode($array);, which returns an array as the result variable with JSON.parse(res) back to page1.php.

As PHP runs on the server, I can't process the JavaScript Ajax response array as PHP array in page1.php.

So, I'm trying to find some correct method to archive this result.

Any advice, guide, or example would be useful.

CodePudding user response:

Buttons in a form and with type="submit" will immediately submit the form. So buttons are not the correct candidate here.

I would recommend using two <select> elements where in you loop over the $array to create the options.

<form method="post" action="page2.php"> 
  <select name="range_start">
    <?php foreach ($array as $item) : ?>
      <option value="<?= $item ?>"><?= $item ?></option>            
    <?php endforeach; ?>
  </select>

  <select name="range_end">
    <?php foreach ($array as $item) : ?>
      <option value="<?= $item ?>"><?= $item ?></option>            
    <?php endforeach; ?>
  </select>        

  <input type="submit"  value="Submit values" />  
</form>

When submitting read out the name attributes that the <select> elements have in the $_POST array.

<?php
if (isset($_POST['range_start']) && isset($_POST['range_end'])) {
  $range_start = $_POST['range_start'];
  $range_end = $_POST['range_end'];
}
  • Related