When my document is ready I have 1 or more identically forms with select and two inputs that I want to show (1 of them based on select dynamically).
For 1 form its pretty simple, but my problem is that forms are generated dynamically like when I have on ready 1 form select tag is looking like this
<button type="button" class="add-document-item btn btn-success btn-sm pull-right">
<i class="glyphicon glyphicon-plus"></i>
</button>
<select id="type" class="form-control">
<option value="1">File 1</option>
<option value="2">File 2</option>
</select>
<div class="col-md-12 system" id="system">
My YII2 active form field...
</div>
<div class="col-md-12 computer" id="computer">
My YII2 active form field...
</div>
If after opening document and there is more than 1 form OR there is one and I adding more by myself dynamically, SELECT id's generating like "type0", "type1", "type2" and same is with form fields id's.
So far I can only switch inputs dynamically only when 1 form is rendered
$(document).ready(function () {
$('#computer').hide();
$(document).on('change', '#type', function () {
var val = $('#type').val();
if (val == 2) {
$('#system').show();
$('#computer').hide();
} else {
$('#computer').show();
$('#system').hide();
}
});
});
My need is to change selected input for every generated form individual. I am stuck for this already for some time. Can anybody can help me?
This javascript I created should do the trick. You'll need to apply this to your own code.
Declare an array with all form elements
Select all elements you are going to loop through
Use forEach and overload it with the array you created
Create an if statement with the right filter set
myArray = document.querySelectorAll('form')
document.querySelectorAll('form').forEach(function(value, index,
myArray){
if (myArray[index].getAttribute('id')=='system'){
console.log('system') //doSomething()
}
})
You can refactor this by replacing the 2th instance of document.querySelectorAll('form') with myArray, but for clarity I'll leave it as is.