Search code examples
javascriptundefinedinnerhtmlvar

JS: change "var y = UNDEFINED" for "var y= blank space" with if


I have a table generated from a textarea filled by users, but some of the time, a cell stays empty (and that's all right).

The thing is that the .innerHTML of that cell is also my var y in a script and when that cell is empty (therefore, undefined), my var y becomes UNDEFINED too (the value, not a string), which makes my whole script fail.

Here's a snippet to show the problem:

<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body><center>

</center></body>

<!--------- script that generates my table from text areas -->
<script>         
				function generateTable() {
                    $('#excel_table1').html("");
					 var n=1;
					 var rows=[];
					 var lng=0;
					 var maxligne=0;
                     
					$('textarea').each(function(){
					  var data = $(this).val();
                        if (data !=''){
					  var rowData = data.split("\n");
					  rows[n] = rowData;
					  lng = rowData.length;
                    if(lng > maxligne)
                    {
                     maxligne=lng   
                    }
                      n++;  
                
                    }
                    }
				
				)
					var table = $('<table />');
					k=0;
					while (k < maxligne) {
						var row = $('<tr />');
						for(var i = 1; i < rows.length; i++)
						{
							var singleRow = rows[i];
                            
                            if(singleRow[k]!= undefined){
							row.append('<td>'+singleRow[k]+'</td>')		
						} else {
                        row.append('<td></td>')	
                            }
                        }
						table.append(row);
						k++;
					}
					$('#excel_table1').append(table);
				}    
			</script>
      
      <textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea> 
					   
		<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
				    
	 <textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
			
			<br>
            
			<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
      
      <div id="excel_table1"></div>
      
<!--------- script that get the data from cells to show it in <H2> -->

<script type="text/javascript">

     function buttonTEST()
               {
                $('#displayCell').html("");
                   
                var x = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[1].innerHTML;
                var y = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[2].innerHTML;
               if (y === undefined) {
    y = " ";
}
                   
             document.getElementById('displayCell').innerHTML = x +" "+ y;
             }
              
 </script>
 
 <br/><br/>
       <h2 id="displayCell"></h2>
 <br/><br/>
      <input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>

As you can see, if you generate a table with only to columns (which is supposed/needs to happen sometimes), we get this error from the console because we're trying to get "innerHTML" from a undefined:

index.html:120 Uncaught TypeError: Cannot read property 'innerHTML' of undefined

A little specification: When that cell is=undefined , I need it to stay undefined, I only want to change the fact that my var y also becomes undefined. So I thought that changing the value of var y (and not the value of that cell, otherwise, the 3rd column, supposed to be empty, would be created just because of an blank space) to a blank space would resolve the problem, but I don't seem to get it right (write it in a correct manner).

Any ideas?


Solution

  • So here's the answer that worked for me:

    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    
    <body><center>
    
    </center></body>
    
    <!--------- script that generates my table from text areas -->
    <script>         
    				function generateTable() {
                        $('#excel_table1').html("");
    					 var n=1;
    					 var rows=[];
    					 var lng=0;
    					 var maxligne=0;
                         
    					$('textarea').each(function(){
    					  var data = $(this).val();
                            if (data !=''){
    					  var rowData = data.split("\n");
    					  rows[n] = rowData;
    					  lng = rowData.length;
                        if(lng > maxligne)
                        {
                         maxligne=lng   
                        }
                          n++;  
                    
                        }
                        }
    				
    				)
    					var table = $('<table />');
    					k=0;
    					while (k < maxligne) {
    						var row = $('<tr />');
    						for(var i = 1; i < rows.length; i++)
    						{
    							var singleRow = rows[i];
                                
                                if(singleRow[k]!= undefined){
    							row.append('<td>'+singleRow[k]+'</td>')		
    						} else {
                            row.append('<td></td>')	
                                }
                            }
    						table.append(row);
    						k++;
    					}
    					$('#excel_table1').append(table);
    				}    
    			</script>
          
          <textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea> 
    					   
    		<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
    				    
    	 <textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
    			
    			<br>
                
    			<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
          
          <div id="excel_table1"></div>
          
    <!--------- script that get the data from cells to show it in <H2> -->
    
    <script type="text/javascript">
    
         function buttonTEST()
                   {
                    $('#displayCell').html("");
                       
    var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
    var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
                   
     if (y ===undefined)
    
        {document.getElementById('displayCell').innerHTML = x ;}
                   
     else
         {document.getElementById('displayCell').innerHTML = x +" "+ y;}
    
        }
                  
     </script>
     
     <br/><br/>
           <h2 id="displayCell"></h2>
     <br/><br/>
          <input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>