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

Updating styled-components variables based on media queries - A step-by-step guide

My current theme setup looks like this: const theme = {color: red}; Within my components, I am utilizing this variable as follows: const Button = styled.button` color: ${props => props.theme.color}; `; I am now faced with the challenge of changin ...

Transforming JSON data into a visually appealing pie chart using highcharts

I'm having trouble loading my JSON string output into a highcharts pie chart category. The chart is not displaying properly. Here is the JSON string I am working with: var json = {"{\"name\":\"BillToMobile\"}":{"y":2.35},"{\ ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

React Context - Ensure synchronized deletion of user posts across routes while maintaining pagination during fetching

INTRODUCTION I am striving to replicate the behavior commonly seen in social networks, where deleting a post by a user results in its automatic removal across all app routes. This functionality is reminiscent of how platforms like Instagram or TikTok oper ...

How the Marvel of jQuery Ignites the Power of

I require some assistance with the callbacks. It appears that they are not functioning properly. I am in the process of creating a jQuery-based game. I have designated a <div id='button'></div> for all the buttons that will be used ...

How can you prevent the upload button from being clicked while a file is being uploaded and

By chance, I stumbled upon an issue that could potentially lead to a major problem with my application. I have developed an application where users can upload videos. Check out the Application here The main concern is that when a user uploads a video and ...

Troubleshooting: Vue.js not triggering method after watching object

I am in need of watching a prop that is an object, so here is my script: <script> export default { watch:{ filter: { handler:(newval)=> { console.log("I have new data",newval) //this works thi ...

Display the length of an array using AngularJS

Hey there, I'm currently having an issue with printing a list where each entry is supposed to follow the format "element X of TOTAL". However, instead of displaying the total value, it appears as blank text. It seems like a simple mistake, but for som ...

Steps for generating a hierarchical menu utilizing data from a CSV file

I am looking to use a CSV file to structure the menu on my webpage. Could someone assist me in creating a nested menu using JavaScript with the provided CSV data? The columns consist of: Level, Menu name, URL 0;"Service"; 1;"Service 1";"http://some-url- ...

Save the status of checkboxes in a JSON file using boolean values of true or false

When a user submits a form, I am retrieving the values of checkboxes and storing them as an array. The simplified form structure is as follows: <!-- gym_create.html - other input fields are omitted for brevity --> <form class="create-gym" role=" ...

Starting service upon startup in Angularjs

I am looking to retrieve configuration data from the server and store it in the global scope within my AngularJS application. My app operates in multiple modes such as development and production, with different external services being used depending on the ...

Choose the option in real-time with Jquery

I'm currently developing a dynamic HTML for Select Option as seen below: item += "<td class='ddl' style='width:40%;'>"; item += "<select>" item += " <option id='list' name='selector' value=" + se ...

NodeJS Express Application Error: Unable to access /url

I've been troubleshooting this issue for an hour now and I'm stumped. I can't seem to access the specified URL. I created a NodeJs Express app, but when I try to access http://localhost:3000/users/login, I receive the error message Cannot GE ...

What are the steps to creating a unique event within an AngularJs service?

In the midst of my AngularJs project, I find myself faced with a dilemma. I have a service designed to manage button events, but I want another service to handle these events indirectly without directly interacting with the buttons themselves. So, my goal ...

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

Error: The Jquery plugin Object #<HTMLDocument> does not have a function called 'observe'

Hello, I recently tried to install the Jquery plugin known as chosen that allows customization of my <select> tag across different browsers. If you're interested, you can find more information about it here. However, after integrating this plugi ...

Tap on the HTML5 video to exit the fullscreen mode

Objective I have successfully implemented a fullscreen video setup that triggers when a link is tapped on a mobile device. To maintain a clean aesthetic, I have hidden the HTML5 video controls using CSS. The desired functionality includes closing the full ...

Using ajax for transferring form data to a different php page

Hello everyone, I'm in need of assistance. I have a form on one PHP page and I want to use AJAX to pass the data to another PHP page that will update my database and then return the results. <form name="profile" class="profile"> < ...

Exploring Opencascade.js: Uncovering the Real Text within a TCollection_ExtendedString

I am currently attempting to retrieve the name of an assembly part that I have extracted from a .step file. My method is inspired by a blog post found at , however, I am implementing it using javascript. I have managed to extract the TDataStd_Name attribut ...

The Angular 2 Router's navigation functionality seems to be malfunctioning within a service

Currently, I am facing an issue with using Angular2 Router.navigate as it is not functioning as expected. import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Router } from '@angular/ ...