Error alert: Code syntax issue detected in Javascript </div>

Currently, I am working on a todolist project from w3schools, which can be found at: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_todo

Here is the output of my work:

After clicking the Add button, an error message appeared saying:

"Uncaught SyntaxError: Unexpected token }" was encountered on line 124.

Surprisingly, there is only a closing div tag </div> on line 124, so it's puzzling why the syntax error occurred. Below is the complete code snippet:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
        <title></title>
        <style type="text/css">

            /* CSS styles go here */

        </style>

    </head>
    <body>
        <!-- HTML content goes here -->

        <script type="text/javascript">

            // JavaScript code goes here

        </script>
    </body>
</html>

In addition, another error occurred as follows:

'Uncaught ReferenceError: newElement is not defined' was reported on line 123.

I have addressed and rectified this issue now.

Answer №1

Simply include the function name in your onclick event like this

<span onclick="newElement()" class="bt">Add</span>

instead of using

<span onclick="javascript:function newElement()" class="bt">Add</span>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
        <title></title>
        <style type="text/css">

            body {
              margin: 0;
              min-width: 250px;
            }
            * {
                box-sizing: border-box;
            }


            ul {
                margin: 0;
                padding: 0;
            }
            ul li{
                cursor: pointer;
                position: relative;
                padding: 12px 8px 12px 40px;
                background: #eee;
                font-size: 18px;
                transition: 0.2s;

                /* make the list items unselectable */
                -webkit-user-select: none;
                -moz-user-select: none;
                -ms-user-select: none;
                 user-select: none;
            }

            ul li:nth-child(odd){
                background: #f9f9f9;
            }

            ul li:hover{
                background: #ddd;
            }

            ul li.checked{
                background: #888;
                color: #fff;
                text-decoration: line-through;
                /*上面是畫斜線~*/
            }

            ul li.checked::before{
                content: '';
                position:absolute;
                border-color: #fff;
                border-style: solid;
                border-width: 0 2px 2px 0;
                top: 10px;
                left: 16px;
                transform: rotate(45deg);
                height: 15px;
                width: 7px;
            }

            .close{
                position: absolute;
                right: 0;
                top: 0;
                padding: 12px 16px 12px 16px;
            }
            .close:hover{
                background-color: #f44336;
                color: white;   
            }
            /* Style the header */
            .header {
                background-color: #f44336;
                padding: 30px 40px;
                color: white;
                text-align: center;
            }

            /* Clear floats after the header */
            .header:after {
                content: "";
                display: table;
                clear: both;
            }

            input{
                margin: 0;
                border: none;
                border-radius: 0;
                width: 75%;
                padding: 10px;
                float: left;
                font-size: 16px;
            }

            .bt{
                padding: 10px;
                width: 25%;
                background: #d9d9d9;
                color: #555;
                float: left;
                text-align: center;
                font-size: 16px;
                cursor: pointer;
                transition: 0.3s;
                border-radius: 0;
            }
            .bt:hover{
                background-color: #bbb;
            }
        </style>

    </head>
    <body>
        <div id="myDIV" class="header">
            <h2>My To do List</h2>
            <input type="text" id="myInput" placeholder="Todo..."/>
            <span onclick="newElement()" class="bt">Add</span>
        </div>

        <ul id="myUL">
            <li>gym</li>
            <li class="checked">javascript</li>
            <li>sleep</li>
        </ul>

        <script type="text/javascript">

                var myList = document.getElementsByTagName('li');
                var i;

                for(i=0;i<myList.length;i++){
                    var span = document.createElement('span');
                    var txt = document.createTextNode("\u00D7"); 
                    span.className='close';
                    span.appendChild(txt);
                    myList[i].appendChild(span);
                }

                var close = document.getElementsByClassName('close');
                var i;
                for(i=0;i<close.length;i++){
                    close[i].onclick = function(){
                        var div = this.parentElement;
                        div.style.display = 'none';
                    }
                }

                var list = document.querySelector('ul');
                //addEventListener():
//              Attach a click event to a <button> element. When the user clicks on the button, output "Hello World" in a <p> element with id="demo":  
//              document.getElementById("myBtn").addEventListener("click", function(){
//                  document.getElementById("demo").innerHTML = "Hello World";
//              });
                list.addEventListener('click',function(ev){
                    if(ev.target.tagName === 'li'){
                        ev.target.classList.toggle('checked'); 
                    }
                },false);

                function newElement(){
                    var li = document.createElement('li');
                    var inputValue = document.getElementById('myInput').value;
                    var t = document.createTextNode(inputValue);
                    li.appendChild(t);//把輸入的東西變成li的子元素
                    if(inputValue === ''){
                        alert('你一定要寫東西!')
                    }else{
                        document.getElementById('myUL').appendChild(li);
                    }
                    document.getElementById('myInput').value='';

                    var span = document.createElement('span');
                    var txt = document.createTextNode('\u00D7');
                    span.className = 'close';
                    span.appendChild(txt);
                    li.appendChild(span);

                    for(i=0;i<close.length;i++){
                        close[i].onclick = function(){
                            var div = this.parentElement;
                            div.style.display = 'none';
                        }
                    }
                }

        </script>
    </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying CSS files in real-time

I've been attempting to dynamically change the CSS file, but I've run into an issue: Whenever I try to alter the style, it seems to work correctly while in "debug mode", showing that the changes are applied. However, once the JavaScript function ...

AngularJS's ng-model is able to handle dynamic changes effortlessly

I am working with an array of objects that can be viewed https://i.sstatic.net/Fg1L8.png Within the dropdown box, I have names listed and a text box that displays the value from the selected object https://i.sstatic.net/rY0ET.png The input box is current ...

Utilizing Google Charts and SteppedAreaChart to visually track the evolution of value over time

My task involves extracting value history data from the database. Every time the value changes, the trigger saves the old value, new value, as well as the date and time of the change. For a web application, I need to visualize these changes. Since the val ...

Arrangement of asymmetrical interactive forms

I am in need of creating a design featuring numerous non-rectangular shapes that are interactive and reveal an image when clicked. The concept is to transform an image of stained glass into a webpage where each pane can be clicked to unveil its colorful ve ...

Sharing JSON data with public/javascripts/X.js in Node/Express: A beginner's guide

Currently facing a challenge with my Express project. Take a look at https://github.com/MoreeZ/help1 and examine ./public/javascripts/budget.js. My goal is to swap the incomeData object to read data from ./incomedata.json I attempted passing it through th ...

A guide to efficiently passing props in Quasar 2 Vue 3 Composition API for tables

I am encountering an issue while attempting to create a custom child component with props as row data. The error message "rows.slice is not a function" keeps appearing, and upon inspecting the parent data, I found that it is an Object. However, the props r ...

Sending arguments to various functions within a single controller in asp.net

I'm seeking assistance, I am working with asp.net core and I require to pass a single parameter to 2 separate actions that return strings. I then need to call these 2 actions in a third action which will render a view based on the results obtained. A ...

The eccentricities of Angular Translate in Firefox and Safari

While everything functions correctly in Chrome, there seems to be an issue with changing the language in Safari and Firefox. angular.module('angularApp') .config(['$translateProvider', function ($translateProvider) { $translateProv ...

Creating a constant in an AngularJS module: The definitive guide to defining module-specific constants

Within a page, numerous Angular modules are present. I have set up a constant for each module containing the version number. var module1 = angular.module('module1').constant('version', '1.2.3'); var module2 = angular.module(& ...

Is there a way to automatically restart my Gulp task when I save changes?

I have a series of Gulp tasks in version 4 that handle tasks like compiling Webpack and Sass, optimizing images, etc. These tasks are automated through a "watch" task while I am working on a project. However, when my watch task is active, saving a file tr ...

How can I loop through a JSON array in JavaScript and execute a function on each element?

I have been attempting to utilize a JavaScript method called f(x,y) with each element in a JSON array. Below is an example of my code: var jsonData = {"a":[1900,1910,1920,1930],"b":[12,19,8,55]} for (var i=0; jsonData.a.length; i++){ f(jsonData.a[i],j ...

Achieving the functionality of making only one list item in the navbar bolded upon being clicked using React and Typescript logic

Currently, in my navigation bar, I am attempting to make only the active or clicked list item appear bold when clicked. At the moment, I can successfully achieve this effect; however, when I click on other list items, they also become bolded, while the ori ...

Using jQuery to create a dynamically moving div that forms an endless wall

In order to create a continuous wall that pulls text from a database and displays it, I've developed the following code: $(function() { var x = 0; var y = 100.0; var z=0; setInterval(function() { x -= 0.1; y -= 0.1; ...

Export default does not actually yield a function; rather, it returns an object

I recently developed a function that is responsible for importing a script from a specified source, calling its exported function, and handling the returned result. To simplify things, I have streamlined the code to focus solely on returning the result. co ...

Utilizing ReactJS to retrieve configuration settings from a YAML file, similar to how it is done

Our team is currently using a full-stack multi-microservice application where the backend java components utilize the spring @value annotation to fetch configuration values from a yml file. This method has been effective and even the Java side of our UI c ...

Creating gifs from an array of base64 strings with gifshot doesn't seem to function properly on Firefox browsers

I am currently attempting to utilize the gifshot library from here in order to generate gifs from a canvas. The process involves capturing the canvas using canvas.toDataURL(), then storing these results in an array, which is subsequently passed to the gifs ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...

Looking for mouseover tooltips in three.js?

Currently, I am working on loading an object similar to this demo. My goal is to display a tooltip or infobox when hovering over a specific part of the object. For example, upon clicking the top button, I would like a tooltip to appear above the box. I hav ...

How to Eliminate Image Flickering While Loading in a React Component

Currently, I am developing a React component that takes an imageUrl and displays it on a canvas with a deliberate 2-second delay to mimic loading time for larger images. However, I have encountered a problem: when the imageUrl changes in the parent compone ...

What is the reason for the maximum alias number in the npm YAML library?

I have been utilizing the npm module yaml to convert complex, interdependent JavaScript objects into a text format that can be easily restored in Javascript. Additionally, I use this package for deep copying of deeply nested objects by serializing and then ...