4
Test scenario
Dynamic form:
function addReg(){
const template = $('#formX > div').last();
const novo = template.clone();
$(template).find('select').each(function(i) {
$(novo).find("select").eq(i).val($(this).val());
});
novo.find('.form-group > label').remove();
novo.find('.form-check-inline').removeAttr('style');
$('#formX').append(novo);
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<form id="formX" method="post" action="action.php" target="_blank">
<div id="registro" class="form-row">
<div class="form-group mr-2">
<label for="item">Item</label>
<select id="item" class="form-control" tabindex="-1" name="item[]">
<option selected>Selecione...</option>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
</div>
<div class="form-group col-md-1">
<div class="form-check form-check-inline" style="padding-top: 30px;">
<input class="form-check-input" type="checkbox" id="bf" value="S" name="bf[]" tabindex="-1">
<label class="form-check-label" for="bf"><b>BF</b></label>
</div>
</div>
</div>
</form>
</div>
<div class="row">
<button form="formX" type="submit" class="btn btn-primary mr-3" tabindex="-1">Salvar</button>
<button class="btn btn-info" onclick="addReg()" tabindex="-1">+</button>
</div>
</div>
Problem
When the checkbox
, it takes the value. When not, it does not take.
Thus, the reference between the records is incorrect.
Example
Exit:
Array
(
[item] => Array
(
[0] => 1
[1] => 3
[2] => 2
[3] => 1
)
[bf] => Array
(
[0] => S
[1] => S
)
)
Expected
The ideal way out would be:
[bf] => Array
(
[0] => N
[1] => S
[2] => S
[3] => N
)
Or even:
[bf] => Array
(
[1] => S
[2] => S
)
Doubts
- What possible solutions to use
array
withcheckbox
in this case? - You can define the value of
checkbox
when unmarked?
Instead of using the names
item[]
andbf[]
, useregistros[0][item]
andregistros[0][bf]
, so in PHP you will have a$_POST['registros']
that will be a array of array associative.– Woss