0

I am having trouble with a certain part of my website, where the user can click many buttons and based on that i need to figure out which one they pressed. There are certain timestamps and they choose which to reserve, i am using foreach to display the buttons so i am not exactly sure how to get it into a bootstrap modal but am unable to. Any ideas? this is the part that displays the timestamps:

<div class="container">
      <h1 class="text-center">Book for date: <?php echo date('d.m.Y', strtotime($date)); ?> </h1>
      <div class="row">
        <div class="col-md-12">
            <?php echo isset($msg)?$msg:""; ?>

        <?php
          $timeslots = timeslots($duration, $cleanup, $start, $end);
          foreach($timeslots as $ts){
          ?>
          <div class="col-md-2">
            <div class="form-group">
              <button class="btn btn-success book" data-bs-toggle="modal" data-bs-target="#myModal"><?php echo $ts ?></button>
            </div>
          </div>

        <?php }  ?>
      </div>
    </div>
  </div>

any ideas what i can do to figure out which button they pressed without it getting too messy?

1 Answers1

0

The snippet below will not actually work here on Stack but should show how you can intercept the click event and access properties from it to use how you see fit. As the clickhandler is defined with function rather than as an arrow function you can use this to refer to the button - or you can use e.target

The PHP script should have access to post variables as defined in the FormData function - set

document.querySelectorAll('button').forEach(bttn=>bttn.addEventListener('click',function(e){
  let url=location.href; // your php script.php perhaps
  let fd=new FormData();
      fd.set('button',this.textContent);
      fd.set('type',e.type);
      fd.set('target',e.target);
      fd.set('content',e.target.textContent);

  fetch( url, { method:'post', body:fd })
    .then(r=>r.text())
    .then(text=>{
      console.info(text)
    })
}))
<button 
  class="btn btn-success book" 
  data-bs-toggle="modal" 
  data-bs-target="#myModal">Timestamp #1</button>
  
<button 
  class="btn btn-success book" 
  data-bs-toggle="modal" 
  data-bs-target="#myModal">Timestamp #2</button>
  
<button 
  class="btn btn-success book" 
  data-bs-toggle="modal" 
  data-bs-target="#myModal">Timestamp #3</button>
  
<button 
  class="btn btn-success book" 
  data-bs-toggle="modal" 
  data-bs-target="#myModal">Timestamp #4</button>
  
<button 
  class="btn btn-success book" 
  data-bs-toggle="modal" 
  data-bs-target="#myModal">Timestamp #5</button>
  
<button 
  class="btn btn-success book" 
  data-bs-toggle="modal" 
  data-bs-target="#myModal">Timestamp #6</button>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46