Require assistance with refreshing the index for the chosen row

I have encountered a problem while attempting to manipulate table rows using Javascript.

Adding new rows works fine, but deleting rows presents an issue. Specifically, the delete function fails if the first row or a row in the middle is deleted (the live code can be viewed here)

The code has been uploaded to PasteBin

 <script type="text/javascript">


        var itemNumber = 0
        var currentRow = 0;
        var selectedRow = 0;

        function theIndex(theRow){
            selectedRow = theRow;
        }

        document.getElementById("addItem").addEventListener("click", function(){

            if (document.getElementById('whatToDo').value != ""){
                currentRow++;

                var table = document.getElementById('myList');
                var row = table.insertRow(currentRow);
                var cell1 = row.insertCell(0);
                var cell2 = row.insertCell(1);
                var cell3 = row.insertCell(2);
                var cell4 = row.insertCell(3);

                itemNumber++;
                // alert(currentRow);
                // cell1.innerHTML = itemNumber;
                cell2.innerHTML = document.getElementById('whatToDo').value;
                cell3.innerHTML = document.getElementById('whenToDo').value;
                cell4.innerHTML = document.getElementById('whereToDo').value;
                row.addEventListener('click', theIndex.bind(null, currentRow));

                document.getElementById('whatToDo').value = "";
                document.getElementById('whenToDo').value = "";
                document.getElementById('whereToDo').value = "";
            }
        });


        document.getElementById("removeItem").addEventListener("click", function(){

            // var theRow = document.getElementById('whatToMark').value;
            var theRow = selectedRow;
            alert("index: " +theRow + " elements: " + currentRow);

            if (theRow > 0){

                document.getElementById("myList").deleteRow(theRow);
                document.getElementById('whatToMark').value = "";
                currentRow--;
                itemNumber--;
            }
            selectedRow = 0;
        });

        document.getElementById("markAsDone").addEventListener("click", function(){

            // var theRow = document.getElementById('whatToMark').value;
            var theRow = selectedRow;

            alert("index: " +theRow + " elements: " + currentRow);

            var table = document.getElementById('myList');
            if (theRow != 0){

                table.rows[theRow].style.setProperty("text-decoration", "line-through");
                document.getElementById('whatToMark').value = "";
            }

            selectedRow = 0;
        });

    </script>

Being new to Javascript, I saw this as an opportunity to expand on the provided exercise and experiment with adding more functionality.

Answer №1

Your method for highlighting the currently selected row has a few flaws:

row.addEventListener('click', theIndex.bind(null, currentRow));

Instead of relying on a global variable, I recommend using a row attribute (or class). Modify the line as follows:

row.addEventListener('click', function(e) {
    document.querySelectorAll('tr[selected]').forEach(function(item) {
        item.removeAttribute('selected');
    })
    row.setAttribute('selected', true);
});

Add the "selected" attribute to the current row and remove it from other rows.

This way, you can easily retrieve the currently selected row by:

var rSelected = document.querySelector('tr[selected]');
var theRow = (rSelected == null) ? 0 : rSelected.rowIndex;

// Your JavaScript code goes here

Answer №2

An issue arises when trying to assign a null value in the following line:

document.getElementById('whatToMark').value = "";

You are encountering a null value error because neither in your JavaScript code nor in your HTML do you define an element with the ID of whatToMark.

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

In Firefox, there is a peculiar issue where one of the text boxes in an HTML form does not display

In my HTML form, users can input their first name, last name, and phone number to create an account ID. The textboxes for first name, last name, and account ID work smoothly on all browsers except Firefox. Surprisingly, the phone number textbox doesn' ...

Problem encountered when trying to use the sharp package in NuxtJS

I attempted to implement this code in my Nuxt project, but it encountered an issue during compilation. Within my plugin/sharp.js file: import vue from "vue" import sharp from "sharp" vue.use(sharp) And in my nuxt.config.js file: plugi ...

What is the process for including a selected-by option in a VIS network graph?

I'm trying to outline the neighboring nodes of the node that has been selected (highlightNearest). Unfortunately, I haven't had success achieving this using JavaScript. Link to StackBlitz ...

Code executing twice instead of once in Javascript

Having trouble with a script in my demo below. When I enter "first input", submit, then click on the returned "first input", it alerts once as intended. However, upon refresh, if I enter "first input", submit, then add "second input", submit, and finally c ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

Tips for sharing a React component with CSS modules that is compatible with both ES Modules and CommonJs for CSS modules integration

Some frameworks, like Gatsby version 3 and above, import CSS modules as ES modules by default: import { class1, class2 } from 'styles.modules.css' // or import * as styles from 'styles.modules.css' However, other projects, such as Crea ...

Having trouble with installing create-react-app for my_app using npm because it seems to be stuck on f

I've hit a roadblock while trying to create a react app on my 2011 MacBook Pro. To start, I downloaded the latest version of Node from their official website. Following the instructions from React documentation, I ran the following commands: npm uni ...

Conceal an element along with its space, then signal the application to show alternative content using React

Greetings everyone! I seek assistance with a React Application that I am currently developing. As a newcomer to the Javascript world, I apologize if my inquiry seems trivial. The application comprises of two main elements: a loader, implemented as a React ...

What is the process for extracting the value of a checkbox generated through JavaScript?

I recently came across a helpful post on Stack Overflow that provided sample code demonstrating how to display multiple list of checkboxes dynamically on a dropdown list. The function in the code was exactly what I needed for my webpage. However, I encount ...

Refreshing the settimeout function through a click event

I'm working on a feature where I use setTimeout to dynamically change the font size of paragraphs. My goal is to have the font size reset when the user clicks on the "reset" button or initiates the timer again. However, I've encountered an i ...

Is it possible for me to save external CDN JavaScript files to my local system?

Normally, I would include scripts from other providers in my application like this: <script src="https://apis.google.com/js/api.js"></script> However, I am considering whether it is feasible to simply open the URL , and then copy and paste th ...

Is it possible for me to utilize this code for logging in through a dialog box?

Here is the code snippet I have on the client side: <p>Username:</p> <p><asp:TextBox ID="tbUsername" runat="server"></asp:TextBox></p> <p>Password:</p> <p><asp:TextBox ID="tbPassword" runat="server ...

When using mongoose, is it possible to add a new item and retrieve the updated array in one endpoint?

My API endpoint for the post operation query using mongoose is not returning the updated array after adding a new item. I have been struggling with this issue for 3 days without any success. Any help would be greatly appreciated. router.post("/:spot ...

Leveraging Polymer web components without the need for a package manager

I am looking to incorporate web components into a static web page without the need for any package manager or JavaScript build process. After referencing , I attempted to import them using unpkg by changing <script type="module" src="node_modules/@pol ...

Issues with CSS properties not functioning correctly within the class.col function

When attempting to apply specific CSS properties to a particular area (e.g., "Dashboard") by assigning the class name "main" to the div.col function in the HTML, I encountered an issue where the CSS property applied affected the entire page. The following ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

employing async/await in the function of a backend API

I'm facing an issue with the following code snippet: service.js module.exports = { getUser }; async function getUser({ data }) { return new Promise((resolve, reject) => { const id = data["id"]; const doc = await db.colle ...

The Three.js scene is failing to render properly on subsequent attempts

Currently, I am in the process of developing a web-based height map generator using Three.js. The project involves utilizing multiple canvases to display the generated height map, individual octaves that make up the map, and a separate canvas to showcase h ...

@mui/x-date-pickers styling for the DatePicker component

Despite numerous attempts, I have been unsuccessful in styling the @mui/x-date-pickers <DatePicker/> component. I've experimented with various methods such as sx={{}}, style={{}}, makeStyles(), .css with the !important rule, renderInput={(param ...

Incorporate React Components into a traditional HTML, CSS, and JavaScript project

Can I incorporate a React Native Component (https://www.npmjs.com/package/react-native-gifted-chat) into my vanilla JavaScript project? Is it feasible to embed a React Native component within a vanilla JavaScript project? If yes, then what is the process ...