I see two possible approaches:
Do not send values to the server that are not filled (using Javascript);
Filter incoming data on the server and remove unfilled inputs.
As data must be validated on the server, option 2 is required but nothing prevents you from using validation on the client along with validation on the server to improve the user experience.
I'll try to explain how it can be done:
Validation on the client
You can use javascript to modify the disabled
of the inputs, this way the browser will send only the inputs that are disabled = false
.
In the example below I use Element.querySelector()
and Element.querySelectorAll()
to search for elements in the DOM, iterate over the result and listen for the change
event % using Element.addEventListener()
.
Each time the status of a checkbox
changes, I loop the DOM starting from% changed, I go up to checkbox
using the read-only property tr
" if you need compatibility with more "exotic" browsers). Starting with Element.parentElement
I'm looking for Element.parentNode
, changing its property tr
property-based input
of disabled
"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 whether the element has been selected or not, just receive the cars and they are not empty.
For this you could use the checked
function along with the < to remove all surplus spaces from the elements of the array. After this you can use this "gambiarra" (which in this case is not we really want to filter only strings that are larger than checkbox
) by joining array_map()
with trim()
to remove the empty strings from our array.
Once this is done, the result will be only the cars received from the previous 0
fined.
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.