Формы обработчика событий JQuery для добавленных строк в таблице - добавленные строки не вызывают события - PullRequest
0 голосов
/ 23 сентября 2019

У меня есть таблица с большинством ячеек в качестве входных данных в форме.Эта версия используется для поиска средней информации.После загрузки страницы учащиеся по умолчанию загружаются со своими оценками.Студенческая ячейка имеет класс class = "student", даже новые добавленные строки получают такой же class = "student".

Существует объект с некоторыми значениями по умолчанию.Я написал некоторый код, который должен (я думаю) прослушать, чтобы увидеть, был ли изменен вход ученика, если это так ... затем обновите остальные столбцы до правильной информации.Это работает с оригинальными студентами, которые были загружены, но не работает с добавленными строками, если вы пытались добавить другого студента.

// Assigning the variables with values given by user
const generic_profile= 'Q1' 


 

// Students you have

let students = {
  'Cindy'   : {age: 9,     m1:80,  m2:90, s1:90 , s2:100},
  'Mark'    : {age: 12,    m1:80,  m2:90, s1:90 , s2:100},
  'Jeff'    : {age: 8,     m1:90,  m2:90, s1:90 , s2:95},
  'Ann'     : {age: 11,    m1:90,  m2:60, s1:90 , s2:100},
  'Jason'   : {age: 5,     m1:95,  m2:30, s1:90 , s2:185},
  'Harvey'  : {age: 10,    m1:100, m2:70, s1:90 , s2:100},
  'Mike'    : {age: 9,     m1:100, m2:80, s1:90 , s2:82},
  'Ross'    : {age: 9,     m1:88,  m2:90, s1:90 , s2:100}
}




//Populates defaultClass dictionary
const defaultClass= (profile) =>{   
    
    // Q1, Q2 or Q3 was elected default loads will auto populate
    if ( profile === "Q1" ){
        let default_loads = ['Cindy' , 'Harvey', 'Mark']            
        return default_loads

    } else if (profile === "Q2") {
        let default_loads = ['Ann', 'Jason' , 'Ross', 'Mark']
        return default_loads
            
    } else if (profile === "Q3") {
        let default_loads = ['Ann', 'Harvey' , 'Jeff', 'Mark']
        return default_loads
        }else {
            return 0
    }
}





// Create Datalist HTML for options
 const dataList =(main_dict) =>{
    var datalist_1 = '<datalist id="student_list">'
    let datalist_2 = ''
    var datalist_3 = '</datalist>'
    
     for (var student in main_dict){
         let temp ='<option value="' + student + '"></option>'
         datalist_2 +=  temp 
     }
     var datalist_final = datalist_1 + datalist_2 + datalist_3
     return datalist_final
    }





//TABLE - DEFAULT RESULTS TO TABLE

const addDefaultToRow =(student_list, datalist_options) =>{
  //Find the table element
  var table = document.getElementById('grade-results')

  // Should alwasys have some values, double checks that it isn't zero. 
  if(student_list.length > 0){
    
    let i= 0
    
    for (let student in student_list){
    //Create an empty ROW <tr> element and add it to the 1st position of the table
    var row = table.insertRow(i);
    

    // Insert new cells (<td> elements) at the 1st-4th column
    var col1 = row.insertCell(0)
    var col2 = row.insertCell(1)
    var col3 = row.insertCell(2)
    var col4 = row.insertCell(3)
    var col5 = row.insertCell(4)
    var col6 = row.insertCell(5)

    //Add the values to the new cells  
        col1.innerHTML = '<input type="text" list="student_list"   class="student"   name="student" value="'  + [student_list[student]] + '">'  +datalist_options
        col2.innerHTML = '<input type="number" list="student_list" class ="age"    name="age" value="'  + students[student_list[student]].age  + '">' 
        col3.innerHTML = '<input type="number" list="student_list" class ="m1"  name="m1" value="'  + students[student_list[student]].m1  + '">'
        col4.innerHTML = '<input type="number" list="student_list" class ="m2"   name="m2" value="'  + students[student_list[student]].m2  + '">'
        col5.innerHTML = '<input type="number" list="student_list" class ="s1"    name="s1" value="'  + students[student_list[student]].s1 + '">'
        col6.innerHTML = '<input type="number" list="student_list" class ="s2"  name="s2" value="'  + students[student_list[student]].s2  + '">'

        i++

    }    
  } 


     //Add Totals Row
     var current_length = document.getElementById("grade-results").rows.length
     var row = table.insertRow(current_length)
    // Insert new cells (<td> elements) at the 1st-6th column
     var col1 = row.insertCell(0)
     var col2 = row.insertCell(1)
     var col3 = row.insertCell(2)
     var col4 = row.insertCell(3)
     var col5 = row.insertCell(4)
     var col6 = row.insertCell(5)
     //Add the values to the new cells  
     col1.innerHTML = 'Average Age'
     col2.innerHTML = 0
     col3.innerHTML = 'Average Math Score';
     col4.innerHTML = 0
     col5.innerHTML = 'Average Science Score';
     col6.innerHTML = 0;  

     present_totals(calculateSum())
}




//User wants to add another row
function addRows() {

    var table = document.getElementById("grade-results")
    let i = document.getElementById("grade-results").rows.length

    var row = table.insertRow(i-1)
    col1 = row.insertCell(0),
    col2 = row.insertCell(1)
    col3 = row.insertCell(2);
    col4 = row.insertCell(3);
    col5 = row.insertCell(4);
    col6 = row.insertCell(5);

    col1.innerHTML = '<input type="text"   list="student_list"  class="student"   name="student" value = "">'  + dataList(students);
    col2.innerHTML = '<input type="number" list="student_list"  class ="age"    name="age"      value="0">';
    col3.innerHTML = '<input type="number" list="student_list" class ="m1"  name="m1"    value="0">';
    col4.innerHTML = '<input type="number" list="student_list"  class ="m2"   name="m2"     value="0">';
    col5.innerHTML = '<input type="number" list="student_list"  class ="s1"    name="s1"      value="0">';
    col6.innerHTML = '<input type="number" list="student_list"  class ="s2"  name="s2"    value="0">';    

    $(document).ready(function(){

        //iterate through each textboxes and add keyup
        //handler to trigger sum event
        $("input").each(function() {

            $(this).keyup(function(){
                present_totals(calculateSum());
            }).click(function(){
                present_totals(calculateSum())
            });
        });
    });
}





//Everytime a click or keyup happens on the table, it updates the totals at the bottom 
  $(document).ready(function(){

    //iterate through each textboxes and add keyup
    //handler to trigger sum event
    $("input").each(function() {

        $(this).keyup(function(){
            present_totals(calculateSum());
        }).click(function(){
            present_totals(calculateSum())
      });;
   });
});




//Everytime a click or keyup happens on the Student, it updates the presets if it exists in our dictionary/object
$(document).ready(function(){
  //handler to trigger if student is changed
    $('input[class="student"]').change(function(){   
        console.log("CHANGE")
        console.log($(this))
        console.log($(this).context.value) 
        var rowSelected = $(this).context.parentElement.parentElement.cells
        var student = $(this).context.value
        // Iterates through each cloumn on changed Student Cell and updates it to presets  i is index that it is iterating and tr is var for the element
       $.each(rowSelected, function(i, tr){
           // It will not update i=0 which is the Student Name that has been selected or changed
            if(i>0){
                if(student in students){
                    var autoFill = [student, students[student].age, students[student].m1, students[student].m2, students[student].s1, students[student].s2 ]
                    var classNameList=  ["student" ,"age", "m1", "m2", "s1", "s2"]
                    tr.innerHTML = '<input type="number" list="student_list" class ="' + classNameList[i] + '"  name="' + classNameList[i] + '" value="'  +autoFill[i]  + '">'
                    console.log(tr)
               }
            }
        });
    });
});




// Adds up all the age, Maths and Science
var calculateSum = () => {

    var table = document.getElementById("grade-results")
    let length_table = document.getElementById("grade-results").rows.length-1
    
    var avg_age = 0;
    var avg_math = 0;
    var  avg_sci  =0;

    var age_array = []
    var m1_array = []
    var m2_array = []
    var s1_array = []
    var s2_array = []
    
    //Use arrays along with index to do the calculations, lets create the arrays first [probably a better way to do this (room for improvement)]
    //iterate through each **Age* and add the values to the array for later calculation
    $(".age").each(function() {
        age =parseInt(this.value)
        //Use if only if the value is number
        if(!isNaN(age) && age.length!=0) {
            // iterate through each power and multiply and add
            age_array.push(age);
        }else{
            age_array.push(0)
        }
    });

     //iterate through each *MAth 1* and add the values to the array for later calculation
     $(".m1").each(function() {
        m1 =parseInt(this.value)
        //Use if only if the value is number
        if(!isNaN(m1) && m1.length!=0) {
            // iterate through each power and multiply and add
            m1_array.push(m1);
        }else{
            m1_array.push(0)
        }
    }); 

     //iterate through each *MAth 2* and add the values to the array for later calculation
     $(".m2").each(function() {
        m2 =parseInt(this.value)
        //Use if only if the value is number
        if(!isNaN(m2) && m2.length!=0) {
            // iterate through each power and multiply and add
            m2_array.push(m2);
        }else{
            m2_array.push(0)
        }
    }); 


     //iterate through each *Sciende 1* and add the values to the array for later calculation
     $(".s1").each(function() {
        s1 =parseInt(this.value)
        //Use if only if the value is number
        if(!isNaN(s1) && s1.length!=0) {
            // iterate through each power and multiply and add
            s1_array.push(s1);
        }else{
            s1_array.push(0)
        }
    });  

     //iterate through each *Science 2* and add the values to the array for later calculation
     $(".s2").each(function() {
        s2 =parseInt(this.value)
        //Use if only if the value is number
        if(!isNaN(s2) && s2.length!=0) {
            // iterate through each power and multiply and add
            s2_array.push(s2);
        }else{
            s2_array.push(0)
        }
    });  
    

    for (var index = 0; index < (length_table); index++){        
       avg_age += age_array[index]
       avg_math +=  m1_array[index] + m2_array[index] 
       avg_sci += s1_array[index] + s2_array[index] 
    }

    avg_age /= age_array.length
    avg_math /= (2* m1_array.length)
    avg_sci /= (2* s1_array.length)


    return [avg_age, avg_math, avg_sci]
    
}





// Add totals at bottom of table
var present_totals =(arr) =>{
    age= arr[0]
    math= arr[1]
    science = arr[2]
  
    var table = document.getElementById("grade-results")
    let i = document.getElementById("grade-results").rows.length
    
    var row = table.rows[i-1]
    
    col1 = row.cells[0], 
    col2 = row.cells[1]
    col3 = row.cells[2];
    col4 = row.cells[3];
    col5 = row.cells[4];
    col6 = row.cells[5];
  
    //col1.innerHTML = "Avg Age"
    col2.innerHTML =  '<input type="number" list="student_list"  class ="power_totals" name="power_totals" value="'  + age.toFixed(1)  + '">' 
    //col3.innerHTML = "Avg Math"
    col4.innerHTML = '<input type="number" list="student_list"  class ="surge_totals" name="surge_totals" value="'  + math.toFixed(1)  + '">'
    //col5.innerHTML = "Avg Science"
    col6.innerHTML =  '<input type="number" list="student_list" class ="energy_totals" name="energy_totals" value="'  + science.toFixed(1)  + '">'
}










const main =() =>{   
    var student_list = defaultClass(generic_profile)    
    var datalist_options = dataList(students)
    addDefaultToRow(student_list, datalist_options)
     
}

main();
<!DOCTYPE html>
<html lang="en" dir="ltr">

  <head>
    <title>System for You</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="test.js" defer></script>  
  </head>



  <body>

    <header>
      <nav class="container">
      </nav> 
    </header>
    
    <section id="top">
      <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ2pprOx6E7ru4w3U0GoHbI9ZMAFHdsS2izq-cNToqaPmLRjbbs" alt="Students">
    </section>

    <section id="main">
      <!--Loads Table-->
      <h1>Calculate average Age<br> Average Scores:</h1>
      <br>
      <p><button onclick="addRows()">Add a new row</button></p> 
      <form action = "test.html" method = "GET">
        <table>
          <!--Form for Application Selection-->
          <thead>
            <tr>
                <th> Name</th>
                <th>Age</th>
                <th>Math Score 1</th>
                <th>Math Score 2</th>
                <th>Science Score 1</th>
                <th>Science Score 2</th>
            </tr>
          </thead>
          <tbody id="grade-results">
          </tbody> 
        </table>
        <br>
        <hr>
        <br>
        <br>
        <br>
        <br>
    


          <input type= "submit" value="Blah Blah ....">
      </form>
      <hr>
    </section>
    
  </body>



</html>
...