How can you create a table cell that is only partially editable while still allowing inline JavaScript functions to work?

Just a few days back, I posted a question similar to this one and received an incredibly helpful response.

However, my attempt at creating a table calculator has hit a snag. Each table row in a particular column already has an assigned `id` to transform the table into a calculator. Unfortunately, this messes up the solution provided in the original question when I try to implement it on my end (resulting in JavaScript reading "kg" as part of a number and displaying the sum as "NaN").

Moreover, there is an unsightly visible text box within each cell above the answer line – not a good look. My existing code features cells that do not present as text boxes but remain editable, offering a much cleaner user experience in my opinion (although functionally redundant, aesthetics matter a great deal to me!).

Below is an outline of the desired code layout. I am aiming for numbers/input to be positioned on the right side of the text box while remaining on the left side of the unit ("kg").

Refer below for a visual representation of what I aim to achieve (with numbers situated on the right).

https://i.sstatic.net/QNxSK.png

Here's the excerpt of the code:

<head>
  <style>
    table {
      border: 1px solid black;
      border-collapse: collapse;
      font-family: Arial, sans-serif;
      margin: 5px;
      width: 100%;
    }
    
    th, td {
      border: 1px solid black;
      border-collapse: collapse;
      font-family: Arial, sans-serif;
      margin: 5px;
      padding: 5px;
    }
  </style> 
</head>
<body>
  <table>
    <tr>
      <th>header1</th>
      <th>header2</th>
    </tr>
    <tr>
      <td>entry1</td>
      <td id="entry1" oninput="myFunction()">4000</td>
    </tr> 
    <tr>
      <td>entry2</td>
      <td id="entry2" oninput="myFunction()">200</td>
    </tr>
    <tr>
      <td>Total</td>
      <td id="total"></td>
    </tr>
  </table> 
      
  <script type="text/javascript">
    document.getElementById("entry1").contentEditable = true;
    document.getElementById("entry2").contentEditable = true;
      
    function myFunction()  {
      var entry1 = document.getElementById("entry1").innerText;
      var entry2 = document.getElementById("entry2").innerText;
      
      var total2 = parseInt(entry1) + parseInt(entry2);
      
      document.getElementById("total").innerHTML = total2;
    }
      
      myFunction();
  </script>  
</body>     

The current setup calculates the numbers from the right column and reflects the sum in the last row. However, I desire units to display here (e.g., "kg") off to the side – non-editable and without being interpreted as numerals in the JavaScript function. Additionally, eliminating the unattractive textbox boundary within the cell would be welcoming.

Is this scenario achievable? Answers are eagerly welcomed!

Answer №1

If an empty string is passed to the parseInt function, it will return NaN. To resolve this issue, modify the following statement from

var total = parseInt(jack2) + parseInt(john2) + parseInt (joe2);

to

var total = (parseInt(jack2) || 0) + (parseInt(john2) || 0) + (parseInt (joe2) || 0);

Additionally, to show the unit next to the number in the right column, include 2 span elements within the td element and utilize flexbox for proper alignment.

To enable editing of the number, add the contentEditable attribute to the span element that contains the number. The span element with the unit will remain non-editable by default.

function myFunction() {
  var jack2 = document.getElementById("jack").innerText;
  var john2 = document.getElementById("john").innerText;
  var joe2 = document.getElementById("joe").innerText;

  var total = (parseInt(jack2) || 0) + (parseInt(john2) || 0) + (parseInt(joe2) || 0);

  document.getElementById("total").innerHTML = total;
}

myFunction();
table {
  width: 100%;
}

table,
tr,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
  font-family: Arial, sans-serif;
  margin: 5px;
}

th,
td {
  padding: 5px;
}

td:last-child {
  display: flex;
  justify-content: space-between;
  border: none;
}

td:last-child span:first-child {
  flex-grow: 1;
  margin-right: 10px;
  outline: none;
  text-align: right;
}

#total {
  display: flex;
  justify-content: flex-end;
}
<table>
  <thead>
    <tr>
      <th>Person</th>
      <th>Weight</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Jack</td>
      <td id="jack" oninput="myFunction()">
        <span contentEditable="true">4</span>
        <span>Kg</span>
      </td>
    </tr>
    <tr>
      <td>John</td>
      <td id="john" oninput="myFunction()">
        <span contentEditable="true">2</span>
        <span>Kg</span>
      </td>
    </tr>
    <tr>
      <td>Joe</td>
      <td id="joe" oninput="myFunction()">
        <span contentEditable="true">3</span>
        <span>Kg</span>
      </td>
    </tr>
    <tr>
      <td>Total</td>
      <td id="total"></td>
    </tr>
  </tbody>
</table>

Answer №2

To prevent the outcome from being "NAN", an if statement is included to check if one of the values is empty and replace it with 0. Within the editing section, two div elements are added - one for modifying the value and the other for appending the text "kg".

<style>
      table {
        border: 1px solid black;
        border-collapse: collapse;
        font-family: Arial, sans-serif;
        margin: 5px;
        width: 100%;
      }

      th, td {
        border: 1px solid black;
        border-collapse: collapse;
        font-family: Arial, sans-serif;
        margin: 5px;
        padding: 5px;
      }
      .input_{
          width: 90%;
          float: left;
      }
      .peso{
          width: 10%;
          float: right;
      }
    </style>
    <table>
      <tr>
        <th>Person</th>
        <th>Weight</th>
      </tr>
      <tr>
        <td>Jack</td>
        <td>
            <div class="input_" id="jack" oninput="myFunction()">1</div>
            <div class="peso">kg</div>
        </td>
      </tr> 
      <tr>
        <td>John</td>
        <td>
            <div class="input_" id="john" oninput="myFunction()">2</div>
            <div class="peso">kg</div>
        </td>
      </tr>
      <tr>
        <td>Joe</td>
        <td>
            <div class="input_" id="joe" oninput="myFunction()">3</div>
            <div class="peso">kg</div>
        </td>
      </tr>
      <tr>
        <td>Total</td>
        <td id="total"></td>
      </tr>
    </table> 

    <script type="text/javascript">
      document.getElementById("jack").contentEditable = true;
      document.getElementById("john").contentEditable = true;
      document.getElementById("joe").contentEditable = true;

      function myFunction()  {
        var jack2 = document.getElementById("jack").innerText;
        var john2 = document.getElementById("john").innerText;
        var joe2 = document.getElementById("joe").innerText;
        if(jack2==""){
            jack2=0;
        }
        if(john2==""){
            john2=0;
        }
        if(joe2==""){
            joe2=0;
        }
        var total2 = parseInt(jack2) + parseInt(john2) + parseInt (joe2);

        document.getElementById("total").innerHTML = total2+" kg";
      }

        myFunction();
    </script>

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

Creating a stylish Go URL bar using HTML and CSS

Looking for some guidance in JavaScript as I am new to it. I want to create a go bar similar to the ones found at the top of browsers using HTML and JS. When the button is clicked, it should navigate to the URL entered in the box. Here's an example of ...

What is the best way to store article IDs using Javascript or HTML?

On my web page, I have a collection of links that users can interact with by clicking and leaving comments. These links are loaded through JSON, each with its unique identifier. But here's my dilemma - how can I determine which link has been clicked? ...

Internet Explorer 9 is not fully extending the width of the box for multiple select options

I am facing an issue with a multiple select input in Internet Explorer 9. The options are not utilizing the full width of the select box, despite having a min-width set on the select element. In Chrome and Firefox, the items fill up the available width pe ...

Incorporate React JS seamlessly into your current webpage

As I delve into learning React and considering migrating existing applications to React, my goal is to incorporate a React component within an established page that already contains its own HTML and JavaScript - similar to how KnockoutJS's `applyBindi ...

retrieving the file directory from a folder with the help of ajax

I am having trouble retrieving a list of files from a specific URL that lists files inside a folder: https://i.sstatic.net/VH22b.png In order to obtain this list of files using JavaScript, I have written the following code: $.ajax({ url: &ap ...

Is the user's permission to access the Clipboard being granted?

Is there a way to verify if the user has allowed clipboard read permission using JavaScript? I want to retrieve a boolean value that reflects the current status of clipboard permissions. ...

Exploring how to use React with a select component featuring objects

Hello, I am new to working with React and I have a question regarding the select component of Material UI. Here's my situation: I am creating functionality for creating and editing a User object. This User object has a primary key and some data, incl ...

Utilize the power of React and Framer Motion to create a visually stunning fade

After creating a preloader that appears when the variable "loading" is set to true, I now want the loader to fade out. This is an overview of my files: On the home page with all the content: return ( <> {loading ? ( ...

Which is better: triggering mouseleave from inside or outside of mouseenter event

As I delve into the basics of jQuery, I stumbled upon mouseenter and mouseleave actions. The question that arose in my mind is: where should I place the mouseleave action? Which approach is more correct and reliable? $(document).ready(function(){ $(&a ...

Use two queries to apply filters to entries in NextJS

Greetings to all! I am currently working on a project in NextJS that involves showcasing a portfolio of works generated from JSON data. [ { "title": "WordPress Plugin for Yandex Recommender Widget", "image" ...

Integrating a conditional statement into the existing for loop code to conceal the covers

My goal is to hide the covers after they are clicked using an if statement within the for loop code. I believe this is where it should be placed. Trying to prevent this action from happening. https://i.sstatic.net/eLSto.png I made an attempt at achievin ...

Can files in a directory be listed using JavaScript without the need for HTML tags?

Currently, I am exploring ways to automate an Angular application using Protractor. During this process, I encountered a situation where I needed to retrieve a list of all the files within a specific folder. In Java, I am aware that we can accomplish this ...

Guide on filling accordion with data from Firebase

I have been working on a web page that retrieves data from my Firestore collection and is supposed to display each document with its corresponding fields. The goal is to populate the accordion with data from Firebase, but unfortunately, nothing is showing ...

Creating an if statement that validates whether all variables have non-null values

I am still getting the hang of javascript and working on some coding projects from my textbooks. The current task involves creating an if statement to check if the values of the elements referenced by the names fname, lname, and zip are all not null. Here ...

Steering your pop up to the top with CSS

Seeking advice on how to position my pop-up at the top of the page and resize it to better fit the screen. Here is where you can find my landing page: yogavoga.com/2weekdiet Grateful for any assistance provided. .modal-content { margin: 5px auto; bac ...

Populate a table cell with a div element in HTML

How can I make a div inside a rowspanned table cell 100% high of the cell? Check out this example for reference: https://jsfiddle.net/gborgonovo/zqohw286/2/ In the provided example, I want the red div to vertically fill the yellow cell. Any suggestions on ...

Tips for retrieving a selected date from an HTML textbox labeled as "Date"

My goal was to find the differences between two dates by utilizing an HTML Date textbox. <input type="text" name="datein" id="datein" value="" class="inputtexbox datepicker" style="display: none" is-Date/> <input type="text" name="dateto" id=" ...

What could be causing the state object in React to not be updating correctly? There seems to be a discrepancy between the expanded and

Displayed on the console is a screenshot showing <br><br> I am working with React.js, and the object displayed in the image is an element within an array that is part of the state object. I'm puzzled by what's happening. The object a ...

What could be the reason why the form is appearing correctly on one landing page but not the other?

I have embedded a Marketo form on two different landing pages on our website. I am using the same JavaScript provided by Marketo for both pages (shown in the code below). However, on page 2, the form field label and cell are displaying incorrectly, appeari ...

morris.js - displaying a dynamic line chart using JSON data

These are the resources I have: clicks.json index.html The contents of my clicks.json file: [ {"day":1,"clicks":"387"}, {"day":2,"clicks":"432"}, {"day":3,"clicks":"316"}, {"day":4,"clicks":"238"}, {"day":5,"clicks":"354"}, {"da ...