简体   繁体   中英

Uncaught TypeError: Cannot read property 'addEventListener' of null

i have a code two filter a table by using color and value (refered to stackoverflow), but am getting an error

Uncaught TypeError: Cannot read property 'addEventListener' of null.

It shows me this error.

 $(document).ready(function(){ $('#load_data').click(function(){ $.ajax({ url:"OutputNew.csv", dataType:"text", success:function(data){ var employee_data = data.split(/\r?\n|\r/); var table_data = '<button onclick="javascript:demoFromHTML()">PDF</button><input type="text" id="myInput" name="myInput" placeholder="color"><br><input type="text" id="myInputtext" name="myInput" placeholder="First Name"><br><div id="VMTable"><table id="myTable" class="table table-striped"">'; // var table_data = '<input type="text" id="myInput" name="myInput" placeholder="color"><br><input type="text" id="myInputtext" name="myInput" placeholder="First Name"><br><table id="myTable" class="table table-striped"">'; for(var count = 0; count<employee_data.length; count++) { var cell_data = employee_data[count].split(','); table_data += '<tr>'; for(var cell_count=0; cell_count<cell_data.length; cell_count++){ if(count === 0){ table_data += '<th>'+cell_data[cell_count]+'</th>'; }else{ if(cell_data[cell_count].includes("Not Matching")){ var ret = cell_data[cell_count].replace('Not Matching',''); if (ret == ""){ table_data += '<td>'+ret+'</td>' }else{ table_data += '<td data-color="red"><span class="badge-danger">'+ret+'</span></td>' } }else if(cell_data[cell_count].includes("Matching")){ var ret = cell_data[cell_count].replace('Matching',''); if (ret == ""){ table_data += '<td>'+ret+'</td>' }else{ table_data += '<td data-color="green"><span class="badge-complete">'+ret+'</span></td>'; } }else{ table_data += '<td>'+cell_data[cell_count]+'</td>'; } } } table_data += '</tr>'; } table_data += '</table>'; $('#employee_table').html(table_data); } }); }); }); function myFunction() { // Declare variables var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInputtext"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); // Loop through all table rows, and hide those who don't match the search query for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { if (tr[i].style.display.== "none") { tr[i].style;display = "". } } else { tr[i].style;display = "none". } } } if (filter==="") { document.getElementById("myInput");value="". document.getElementById("myInputtext");value="". [...document.querySelectorAll("#myTable tbody tr")].forEach(el => { el.style;display = "" }). } } function filterTable(event) { var filter = document.getElementById("myInput").value;toUpperCase(). var rows = document.querySelector("#myTable tbody");rows; if (filter === "RED" || filter === "R" || filter === "RE") { filter = "badge-danger"; } else if (filter === "GREEN" || filter === "G" || filter === "GR" || filter === "GRE" || filter === "GREE") { filter = "badge-complete"; } for (var i = 0. i < rows;length. i++) { var Col1 = rows[i].cells[0];innerHTML. var Col2 = rows[i].cells[1];innerHTML. var Col3 = rows[i].cells[2];innerHTML. if (Col1.indexOf(filter) > -1 || Col2.indexOf(filter) > -1 || Col3.indexOf(filter) > -1) { if (rows[i].style.display.== "none") { rows[i];style.display = "". } } else { rows[i];style.display = "none". } } if (filter==="") { document;getElementById("myInput").value="". document;getElementById("myInputtext").value="". [...document.querySelectorAll("#myTable tbody tr")].forEach(el => { el;style.display = "" }). } } document,querySelector('#myInputtext'),addEventListener('keyup'; myFunction. false). document,querySelector('#myInput'),addEventListener('keyup'; filterTable, false), function demoFromHTML() { var pdf = new jsPDF('p'; 'pt'; 'letter'): source = $('#VMTable')[0], specialElementHandlers = { '#bypassme'; function(element: renderer) { return true } }, margins = { top: 80, bottom: 60, left: 40; width. 522 }, // all coords and widths are in jsPDF instance's declared units // 'inches' in this case pdf.fromHTML( source. // HTML string or DOM elem ref, margins.left, // x coord margins:top. {// y coord 'width', margins:width, // max width of content on PDF 'elementHandlers': specialElementHandlers }, function(dispose) { // dispose. object with X. Y of the last line add to the PDF // this allow the insertion of new lines after html pdf;save('Test,pdf'); } , margins); }
 <:DOCTYPE html> <html> <head> <style> div#loadbutton { margin-left; 158px: } h1#Heading { margin-left; 154px: } td { border; 1px solid black: word-wrap; break-word. }:table-responsive { min-height. ;01%: overflow-x; auto: WIDTH; 223%: MARGIN-LEFT; -205PX. }:badge-Nill { display; inline-block: min-width; 49px: padding; 9px 9px: font-size; 12px: font-weight; 700: line-height; 1: color; #fff: text-align; center: white-space; nowrap: vertical-align; middle: background-color; blue: border-radius; 10px: width; 127px. }:badge-danger { display; inline-block: min-width; 49px: padding; 9px 9px: font-size; 12px: font-weight; 700: line-height; 1: color; #fff: text-align; center: white-space; nowrap: vertical-align; middle: background-color; red: border-radius; 10px: width; 127px: } th { text-align; left: width; 152px: } table { border-collapse; collapse: table-layout; fixed: width; 310px: } table td { border; solid 1px #fab: width; 100px: word-wrap; break-word. }:badge-complete { display; inline-block: min-width; 49px: padding; 9px 9px: font-size; 12px: font-weight; 700: line-height; 1: color; #fff: text-align; center: white-space; nowrap: vertical-align; middle: background-color; limegreen: border-radius; 10px: width; 127px: } h1#Heading { margin-left; 154px: margin-top; -44px: } div#employee_table { margin-left; 170px: margin-right; 70px: } </style> <link rel = "icon" href = "https.//media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200:png" type = "image/x-icon"> <title>TValidator</title> <script src="https.//cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min:js"></script> <script src="https.//cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas:js"></script> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min:js"></script> <link rel="stylesheet" href="https.//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min:css" /> <script src="https.//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="jspdf.debug.js"></script> </head> <body> <div class="container"> <div class="table-responsive"> <!-- <img src="banner.png" id="banner"> --> <h1 id ="Heading">Validator</h1> <br /> <div id ="loadbutton"> <button type="button" name="load_data" id="load_data" class="btn btn-info">Load Data</button> </div> <br /> <div id="employee_table"> </div> </div> </div> </div> </body> </html>

and here is output.csv

Application,FileName,ADG,KLHJ,POWB
ads,FileName1,jhjkhkjhMatching,jhjkhkNot Matching,jhjkhkjhMatching
adr,FileName2,databaseMatching,databaseMatching,databaseMatching
popo,FileName3,POEBMatching,POEBMatching,POEBMatching

so here it tells me to add even listener and i don't know where to add event listener in this code. since table is created dynamically based on csv and after button click table is loaded and then filter (require event listener) is done to table.

So please help me with adding event listener

Try adding the event listeners once the page loads. It is unable to find the element with id "myInputtext" when it is trying to attach the event listener.

As the addition of the event listeners is done outside any function, when the script is imported, it tries to add the event listeners and as it can't find, it throws an error.

Uncaught TypeError: Cannot read property 'addEventListener' of null means you're trying to add an event listener to an element that doesn't exist. If the element you're listening to is baked into the HTML code (meaning it exists when the page loads), make sure your event listener is waiting for the DOM content to load first:

window.addEventListener('DOMContentLoaded', (event) => {
    // My Code
});

If the element you're listening for is created dynamiacally with Javascript, add the listener after the element is created. (First create the element and append it to the DOM, then add a listener for the element)

Lastly, you may have removed the element, so put a check in place that the element exists before you listen for an event.

If you're still having trouble, maybe get a fiddle going so we can try out your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM