Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

50
Views
How can I dynamically select input field in dynamically generated forms with Javascript/jQuery?

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?

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

This javascript I created should do the trick. You'll need to apply this to your own code.

  1. Declare an array with all form elements

  2. Select all elements you are going to loop through

  3. Use forEach and overload it with the array you created

  4. 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.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.