How to group radio Buttons

Asked

Viewed 289 times

2

Hello,

I’m wanting to make a way that these radio Buttons get the same name inside a form, but that are marked by question.

Because I’m going to send this form to a PHP and pick it up there as an array, these questions will come from the database, so I don’t put different names because it might have 2 questions or 30 questions, there is no way I leave predefined in PHP how many question and which names will come by POST.

<div class="col-12">
  <div class="form-row">
    <div class="form-group">
      <label>Pergunta 1</label>
      <input type="radio" name="radio">
      <input type="radio" name="radio">
      <input type="radio" name="radio">
      <input type="radio" name="radio">
      <input type="radio" name="radio">
    </div>
  </div>
  <div class="form-row">
    <div class="form-group">
      <label>Pergunta 2</label>
      <input type="radio" name="radio">
      <input type="radio" name="radio">
      <input type="radio" name="radio">
      <input type="radio" name="radio">
      <input type="radio" name="radio">
    </div>
  </div>
</div>

Somebody help me, please?

1 answer

2


You can set the name as an array, it would look like this:

<div class="col-12">
  <div class="form-row">
    <div class="form-group">
      <label>Pergunta 1</label>
      <input type="radio" name="resposta[1]">
      <input type="radio" name="resposta[1]">
      <input type="radio" name="resposta[1]">
      <input type="radio" name="resposta[1]">
      <input type="radio" name="resposta[1]">
    </div>
  </div>
  <div class="form-row">
    <div class="form-group">
      <label>Pergunta 2</label>
      <input type="radio" name="resposta[2]">
      <input type="radio" name="resposta[2]">
      <input type="radio" name="resposta[2]">
      <input type="radio" name="resposta[2]">
      <input type="radio" name="resposta[2]">
    </div>
  </div>
</div>

and in your php:

foreach ($_POST['resposta'] as $resposta) {
    // código
}

Always remember to assign a value in the input!

Browser other questions tagged

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