Question

I'm trying to use innerHTML, but whenever I run it and press F12 on Google Chrome I get this error:

Uncaught ReferenceError: fun is not defined

Here's my code:

<script type="text/javascript">
    function fun(){
        document.getElementById('checklist').innerHTML =
        "<li> <input type="checkbox" > <label >Checkbox 1</label> </li>";
    }
</script>
    <p><input type="button" onclick="fun()" value="Add"/></p>

</div>
     <h3></h3>
</div>

 <div class="scroll" >
       <ul class="listacheck" id="checklist">

       </ul>

I don't really get why it's saying the function is not defined, I would be greatfull if anyone could help :)

Was it helpful?

Solution

The line

"<li> <input type="checkbox" > <label >Checkbox 1</label> </li>";

is not escaped properly with the embedded quotes around "checkbox". This causes the parser to fail during the definition of fun. You can use single quotes

"<li> <input type='checkbox' > <label >Checkbox 1</label> </li>";

or escape the double quotes:

"<li> <input type=\"checkbox\" > <label >Checkbox 1</label> </li>";

or use single quotes to define the string:

'<li> <input type="checkbox" > <label >Checkbox 1</label> </li>';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top