I see two possible approaches:
- Do not send values that are not filled in to the server (using Javascript);
- Filter incoming data on the server and remove unfilled inputs.
Since data should be validated on the server, option 2 is mandatory but nothing prevents you from using client validation along with server validation to improve user experience.
I’ll try to explain how it can be done:
Validation in the client
You can use javascript to modify the property disabled
inputs, this way the browser will send only inputs that are disabled = false
.
In the following example use Element.querySelector()
and Element.querySelectorAll()
to search for the elements in the GIFT, I spend time on the result and listen to the event change
using Element.addEventListener()
.
Each time the state of a checkbox
changes, I go through the DOM starting from the checkbox
altered, I go up to the tr
using the read-only property Element.parentElement
(you can use Element.parentNode
if you need compatibility with more "exotic" browsers). Starting from tr
I seek the input
, changing your property disabled
property-based checked
of checkbox
"clicked".
let checks = document.querySelectorAll('.check')
for (let i=0, l=checks.length ; i<l ; i++) {
checks[i].addEventListener('change', function(event) {
let tr = this.parentElement.parentElement.parentElement
tr.querySelector('.carro').disabled = !this.checked
})
}
<table>
<thead>
<tr>
<th>Carro</th>
<th>Selecione</th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="Carro[]" class="carro" value="Modelo 1"></td>
<td>
<label>
<input class="check" type="checkbox" checked>
</label>
</td>
</tr>
<tr>
<td><input name="Carro[]" class="carro" value="Modelo 2"></td>
<td>
<label>
<input class="check" type="checkbox" checked>
</label>
</td>
</tr>
<tr>
<td><input name="Carro[]" class="carro" value="Modelo 3"></td>
<td>
<label>
<input class="check" type="checkbox" checked>
</label>
</td>
</tr>
</tbody>
</table>
Server Validation
Apparently there is no need for you to receive on the server if the element was selected or not, just receive the cars and these are not empty.
For this you could use the function array_map()
along with the function trim()
to remove all excess spaces from the array elements. After that you can use this "gambiarra" (which in this case is not because we really want to filter only strings that have larger size than 0
) joining together array_filter
with strlen
to remove empty strings from our array.
Once this is done the result will only be the cars received from form
previous that are filled.
Example:
<?php
$carros = ["Modelo 1", "", " ", "Modelo 2"];
// Remover espaços
$carros = array_map('trim', $carros);
// Remover elementos vazios
$carros = array_filter($carros, 'strlen');
Repl.it with the code working.