Skip to content
Advertisement

Javascript, get the number of time an imput value occured in Table

I am generating a table onclick, in my html when this function triggers

let start = 1;
let end = start+14
function generateTab(tab){
    tabRow =   `<div>
                    <table class="table" id="gen-table">`;
                        for (let i = start; i <= end; i++) 
                            tabRow +=
                            `<tr>
                                <td>${i+1}</td>
                                <td>
                                    <input type="text" name="tab[${i}]"
                                     id="tab[${i}]" size="10" 
                                     onchange="myFunc(this, ${i})" 
                                     value="${JSON.parse(tab)[`${i}`] ? 
                                     JSON.parse(tab)[`${i}`].name :''}">
                                </td>
                            </tr>`;
                        tabRow +=
                        `</tbody>
                    </table>
                </div>`
    start+= 15;
    end= start+ 14;
    return tabRow ;
}

And The Table Looks like this

This is how the table is.

In the input there is an onchange() function. IN that function I need to get how many times the value is present in the table. For example if I change the first row, I should get 1. Because there were two rows with the value “Apple”. And I just changed one. So, there is now only 1 row with value “Appple”.

Here is my myFunc function

function myFunc (data, i){
    var input= document.getElementById('box['+i+']').value;
    var table = document.getElementById("gen-table");
    var occurance= table.innerHTML.split(/W+/).filter(
        function(v){return v==input}
    ).length;
   console.log(occurance);
} 

I cannot seem to get it work. Any help on how to get it in the myFunc will be appreciated.

Advertisement

Answer

There’s a typo in your myFunc function (“box[” vs “tab[“). This is how I’d do it:

function myFunc (data, i){  
  var input= document.getElementById('tab['+i+']').value;  
  var table = document.getElementById("gen-table");  
  var occurance = table.querySelectorAll("input[value="+input+"]");  
  console.log(occurance.length);  
}

Also, constructing that first string is a little messy, so I’d do it like this:

for (let i = start; i <= end; i++) {  
let tabName = JSON.parse(tab)[i] ? JSON.parse(tab)[i].name :'';  
//...  
value="${tabName}">  
//...  
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement