php - JavaScript getElementById null values error and how to avoid it -


i have created form user inputs minimum , maximum number of textareas can added page. generates code below in order pick jscript:

$minimum .= '<div id="k'.$i.'">'.$min[$i].'</div>'; $maximum .= '<div id="h'.$i.'">'.$max[$i].'</div>'; 

in jscript, defined loop catch above div tags , theirs innerhtmls numbers , put in array.

var mincount = []; var maxcount = []; for(var k=1; k<101; k++) {     mincount[k] = parseint(document.getelementbyid("k"+k).innerhtml, 10);     maxcount[k] = parseint(document.getelementbyid("h"+k).innerhtml, 10); } 

the k defined 100. so, know problem, because if there less 100 textareas, getelementbyid having null values.

so, gives error: uncaught typeerror: cannot read property 'innerhtml' of null

but must defined 100. so, there option can work this:

if(mincount[k] == null) {mincount[k] = ""} // in order avoid null values. 

this isn't working. still error.

the easier solution give elements same class, , select elements class. don't see reason why every element must have own id.

$minimum .= '<div class="k">'.$min[$i].'</div>'; $maximum .= '<div class="h">'.$max[$i].'</div>'; 

then in javascript:

var mincount = []; var minelements = document.queryselectorall('.k'); (var = 0, l = minelements.length; < l; i++) {     mincount.push(parseint(minelement[i].innerhtml, 10));     // if content purely numeric, unary plus simpler:     // mincount.push(+minelement[i].innerhtml); } 

same of maxcount.

or @adeneo suggested, if javascript code served through php , have access $min array, do

var mincount = <?php echo json_encode($min); ?>; 

then don't how touch dom.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -