InnerHTML syntax for creating the button in the cell is not functioning properly with the HTML onclick event

I'm facing an issue with my code where I am trying to insert a button into a table cell. The button has an action assigned to it using the onclick attribute. However, no matter how I try to use single quotes with or without backslashes in the syntax onclick='function_name', I keep encountering the error message "editRow is not defined" and the button doesn't trigger any action when clicked. It seems like the HTML is interpreting the single quote I entered in the cell's text as double quotes. I'm unsure of what is causing this problem.

var info = [{
  "firstName": "aaa",
  "lastName": "A"
}, {
  "firstName": "bbb",
  "lastName": "B"
}, {
  "firstName": "ccc",
  "lastName": "C"
}];
function display(info) {
var table=document.getElementById("table");
var Length=info.length;

for(var i=0; i<info.length; i++)
{
    var row = table.insertRow(i+1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
                            
    cell1.innerHTML = info.[i].firstName;
    cell2.innerHTML = info.[i].lastName;
    
    var editButtonHTML = "<input type=button value=Edit class=edit id=edit-button"+(i+1)+" onclick=\'editRow("+(i+1)+")\'>";
    
    cell3.innerHTML=editButtonHTML;
}//end for  

function editRow()
{
    console.log("inside editRow "+(i+1));
}

//console.log(table.innerHTML);
}//end display

The solution provided by @Rohit Kumar works when running the code in Firefox browser. But when running it in the addon extension using jpm, it gives:

ReferenceError: editRow is not defined

Also, when I print the HTML code in the table, I see double quotation marks instead of singles.

I also attempted adding an event listener after the button element, but unfortunately, it did not work as expected.

butId="edit-button"+(i+1);
    console.log("button id is: "+butId);
    
    document.getElementById(butId).addEventListener('click',editRow);

Answer №1

There were a few issues with the code:

  1. The object info was not initially defined.
  2. The edit method was incorrectly called, resulting in the same message being displayed regardless of the button clicked.
  3. A bug caused the function to return "inside editRow 4" when row number 4 did not exist. This was due to using the last value of I from the for loop.

  4. It is important to ensure that a blank tr tag is defined inside the table, otherwise the row.insertRow function will not work as expected.

var info = [{
  "firstName": "aaa",
  "lastName": "A"
}, {
  "firstName": "bbb",
  "lastName": "B"
}, {
  "firstName": "ccc",
  "lastName": "C"
}];
var table = document.getElementById("table");
var storageLength = info.length;

for (var i = 0; i < info.length; i++) {
  var row = table.insertRow(i + 1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);

  cell1.innerHTML = info[i].firstName;
  cell2.innerHTML = info[i].lastName;

  var editButtonHTML = "<input type=button value=Edit class=edit id=edit-button" + (i + 1) + " onclick=\'editRow(" + (i + 1) + ")\'>";

  cell3.innerHTML = editButtonHTML;
} //end for
   //Made an edit here
function editRow(rowindex)
{
    console.log("inside editRow "+(rowindex));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table id="table" border='1'>
  <tr></tr>
</table>

Answer №2

To enhance your code, switch the usage of single quotes and double quotes by enclosing the string editButtonHTML with single quotes. Then, utilize double quotes around all tag attributes within the HTML.

rowNumber = i+1;
var editButtonHTML = '<input type="button" value="Edit" class="edit" id="edit-button"' + rowNumber + ' onclick="editRow(' + rowNumber + ')">';

Consider refraining from outputting HTML directly as a string. Instead, consider using jQuery to attach a new button object to the DOM. This way, you can create the button, set the tag attributes, and define the onclick event action more efficiently.

Answer №3

This solution has been effective for me, I recommend giving it a try.

    function displayInformation(data) {
var table=document.getElementById("table");
var length=data.length;


    for(var index=0; index<data.length; index++)
    {
        var row = table.insertRow(index+1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);

        cell1.innerHTML = data[index].firstName;
        cell2.innerHTML = data[index].lastName;

       var editButtonHTML = "<input type=button value=Edit class=edit id=edit-button"+(index+1)+" onclick='editTableRow("+(index+1)+")'>";

        cell3.innerHTML=editButtonHTML;
    }//end for  
}

The following edit function is missing its parameter:

   function editTableRow(index)
{
    console.log("inside editTableRow "+(index+1));
}

Answer №4

When you add a DOM element as a string in your example, you call the 'editRow' function on click in the global (window) context.

Instead of that approach, it's better to create the element, bind the context with the necessary parameters, and append it as a child DOM element:

var editButtonHTML = document.createElement('input');
editButtonHTML.type = 'button';
editButtonHTML.value = 'Edit';
editButtonHTML.className = 'edit';
editButtonHTML.id = 'edit-button' + (i+1);
editButtonHTML.onclick = editRow.bind(this, i + 1);
cell3.appendChild(editButtonHTML);

Provided here is the complete solution:

var info = [{
  "firstName": "aaa",
  "lastName": "A"
}, {
  "firstName": "bbb",
  "lastName": "B"
}, {
  "firstName": "ccc",
  "lastName": "C"
}];

function display(info) {
  var table = document.getElementById("table");
  var Length = info.length;

  for(var i = 0; i < info.length; i++){
      var row = table.insertRow(i);
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      var cell3 = row.insertCell(2);

      cell1.innerHTML = info[i].firstName;
      cell2.innerHTML = info[i].lastName;

      var editButtonHTML = document.createElement('input');
      editButtonHTML.type = 'button';
      editButtonHTML.value = 'Edit';
      editButtonHTML.className = 'edit';
      editButtonHTML.id = 'edit-button' + (i + 1);
      editButtonHTML.onclick = editRow.bind(this, i + 1);
      cell3.appendChild(editButtonHTML);
  }

  function editRow(num){
      console.log('inside editRow ' + num);
  }
}

display(info);

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

Is it possible to utilize both body-parser and Formidable simultaneously?

I've been working on a problem for a few days now, but I'm having trouble understanding certain aspects of it. My website is built using NodeJS and ExpressJS, with form handling done through body-parser. var adName = req.body.adName; var adMess ...

Combining specific columns in the user interface grid

I need to customize a UI grid by merging some middle columns to achieve the following layout: Name | Address | Comment | Job | College | Married ---------------------------------------------------------- Keshvi | India | New | Not applicable ...

Open a JavaScript file to retrieve data from a nearby JSON object

I've been trying to access a local JSON file using a JavaScript file, but for some reason it's not working. Even though I'm sure the URL is correct, the code keeps failing to retrieve data from the JSON object. JavaScript file: var pieData ...

"Exploring the possibilities of Ajax in conjunction with Sol

I recently completed a tutorial on Ajax Solr and followed the instructions in step one. Below is the code I wrote: header.php: <script type="text/javascript" src="static/js/ajax-solr/core/Core.js"></script> <script type="text/javascript" s ...

Conceal the parent div from its sibling within the same parent container

My goal is to conceal a parent component from its child element. I attempted to achieve this by using the parent component as a background while adding additional backgrounds to the child elements for overriding purposes. However, this method did not work ...

Exploring the functionalities of the componentDidUpdate() method in React JS

In my project, I am trying to dynamically change an API parameter using a click function and render new data accordingly. The issue I encountered is that when I trigger the componentDidUpdate method with an onclick event listener, the first click works fin ...

The asynchronous AJAX request is finished after the function call has been made. This can be achieved without using

I am in search of a solution that will allow an AJAX API call to finish before the containing function does without relying on jQuery as a dependency for just one REST call... After going through multiple solutions, all of which involve using jQuery, I ca ...

Angular 6+ Unveiled: The Magic of Transparent Wrapper Components

One standout feature of Vue.js is the ability to dynamically assign new attributes to a specific element within the template, which is referred to as Transparent Wrapper Components In this example, I am able to pass all existing HTML attributes to a speci ...

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

Using AngularJS to incorporate ng-include with ng-click functionality

I am trying to figure out a way to insert HTML that is specifically optimized for the controller into an alert div. Unfortunately, I have been unsuccessful so far... <script type="text/ng-include" id="login.html"> <form data-select="exepti ...

TinyMCE generates HTML code with embedded tags

Hey there, I'm currently facing an issue with TinyMCE that I just can't seem to solve. I've browsed through some related posts but haven't found a solution that works for me... For example: When I input something in my back office, ...

Methods to Maintain Consistent HTML Table Dimensions utilizing DOM

I am facing an issue with shuffling a table that contains images. The table has 4 columns and 2 rows. To shuffle the table, I use the following code: function sortTable() { // Conveniently getting the parent table let table = document.getElementById("i ...

What crucial element is absent from my array.map function?

I have successfully implemented a table with v-for in my code (snippet provided). However, I am now trying to use Array.map to map one array to another. My goal is to display colors instead of numbers in the first column labeled as networkTeam.source. I at ...

Why are the class variables in my Angular service not being stored properly in the injected class?

When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server. However, in getServerNotificationToken() function, this.userID is returned as 'undefined' to the server and also prints as such. I am puzz ...

Retrieve no data from Firebase using Cloud Functions

I am a beginner with Google Firebase and Cloud Functions, and I recently attempted a basic "hello world" program: Established a connection to Cloud Firestore [beta], which contains over 100,000 records. Retrieved the top record from the database. Below ...

Success callback for tracking conversions on Google

When an ajax call is successful, I am triggering the Google conversion tracking code. Along with tracking the conversion, I also need to change the window location. Is there a method to receive a callback when the conversion tracking is successful, so tha ...

How to efficiently update a nested array within the state of a React

Although the onChange function is working as expected, I am facing issues with updating the features in the state. Despite numerous attempts, I haven't been able to find examples similar to what I'm trying to achieve, so I decided to seek help. ...

AJAX isn't quite cooperating - it seems that only the error callback is getting

Even though I have specified both success and error callbacks, the error callback is being triggered even when the status code is 200. In addition, I am also making a curl call to another php file within registry.php. This is what I have attempted: $.aj ...

Printing content to an HTML page using Node.js

I'm seeking advice on using Node JS, AJAX, and other related technologies. My goal is to display the content of a JSON file on my HTML page. While I've been successful in saving new objects to the JSON file, I'm struggling to find an effecti ...

Retrieving a JSON object using a for loop

I'm working on a basic link redirector project. Currently, I have set up an Express server in the following way: const express = require('express'); const app = express() const path = require('path'); const json = require('a ...