Is it wrong to create checkboxes with the same name?

Asked

Viewed 126 times

1

Create several checkbox with the same name can be considered wrong? Since the value is what defines the dado of checkbox. Or should I really have names different?

<tr>
  <td>Status</td>
  <td colspan="3">
    <input type="checkbox" name="chk_stat[]" value="single" id="chk_stat">single

    <input type="checkbox" name="chk_stat[]" value="married" id="chk_stat">Married

    <input type="checkbox" name="chk_stat[]" value="divorcee" id="chk_stat">Divorcee

    <input type="checkbox" name="chk_stat[]" value="student" id="chk_stat">Student
  </td>
</tr>
  • Wrong is to put the same id on all elements.

  • This way no, what is wrong is the repetition of Ids, Ids should be unique (Why it is considered wrong/bad to repeat an HTML ID?). The form of the Names is OK, they will be treated with a vector when received in the back-end.

  • Assuming the name was only name="chk_stat" would no longer be correct?

  • Then will always return the last marked. It would be incorrect to checkbox.

2 answers

0

That is correct.

Avoid just repeating the ID as they should be unique.

in PHP you can recover them with foreach

foreach($_POST['chk_stat'] as key){
   //tratamento para cada combo selecionado
}

0


With the same name only makes sense even use as array (adding [] at the name, as you are doing). Unlike radio, usually each checkbox has a name unique, but there is no problem in using this way.

The incorrect is to use the same name without the brackets, because the back-end will receive only the last checkbox marked.

The only possible problem, perhaps, is that if you mark only the last one, for example, the array received in the back-end will always start from the index [0], that is to say:

Array ( [0] => student )

Browser other questions tagged

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