Array function malfunctioning

How do I assign values to the input boxes? The gng() function is not working correctly when my code runs. Instead of seeing the expected result, I only see the string "gng()" in the input box.

<div id="yeni" style="position: absolute; top: 50px; left: 30px; width: 700px; height: 400px; "> </div>

<script>
  var tbl = document.createElement('table');
  var tr = [];
  var td = [];
  var rowcount = 5;
  var columncount = 3;
  var dataarray = [["1", "red", " <input value=\"gng(9,5)\">"],
      ["2", "white", " <input value=\"gng(3,5)\">"],
      ["3", "black", " <input value=\"gng(4,5)\">"],
      ["4", "green", " <input value=\"gng(1,5)\">"],
      ["5", "gray", " <input value=\"gng(2,5)\">"]]

  for(s = 0; s < rowcount; s++) {
    tr[s] = document.createElement('tr');
    for(i = 0; i < columncount; i++) {
      td[i] = document.createElement('td');
      td[i].innerHTML = dataarray[s][i];
      tr[s].appendChild(td[i]);
    }
    tbl.appendChild(tr[s]);
  }
  document.getElementById('yeni').appendChild(tbl);
  function gng(a, b) {var c = a / b;return c;}
</script>

Answer №1

" <input value=\"gng(9,5)\">"
is considered a string in programming, meaning it is simply literal text data. The inclusion of gng(9,5) within the string does not trigger the function gng. To properly incorporate the result of gng(9,5), you must concatenate the surrounded parts of the string with an invocation like so:
' <input value="' + gng(9,5) + '">'
. In this revised version, I have switched the double quotes to single quotes which are interchangeable in JavaScript – using single quotes eliminates the need to escape double quotes inside the string.

Here is the modified code block:

function gng(a, b) {
  var c = a / b;
  return c;
}

var tbl = document.createElement('table');
var tr = [];
var td = [];
var i; // ensure all variables are declared!
var s; // note that without declaring s and i, they become implicit globals
var rowcount = 5;
var columncount = 3;
var dataarray = [
    ["1", "red", ' <input value="' + gng(9,5) + '">'],
    ["2", "white", ' <input value="' + gng(3,5) + '">'],
    ["3", "black", ' <input value="' + gng(4,5) + '">'],
    ["4", "green", ' <input value="' + gng(1,5) + '">'],
    ["5", "gray", ' <input value="' + gng(2,5) + '">']
  ];

for(s = 0; s < rowcount; s++) {
  tr[s] = document.createElement('tr');
  for(i = 0; i < columncount; i++) {
    td[i] = document.createElement('td');
    td[i].innerHTML = dataarray[s][i];
    tr[s].appendChild(td[i]);
  }
  tbl.appendChild(tr[s]);
}
document.getElementById('yeni').appendChild(tbl);
<div id="yeni" style="position: absolute; top: 50px; left: 30px; width: 700px; height: 400px; "> </div>

If your target browsers support template literals, you can use them instead:

["1", "red", `<input value="${gng(9,5)}">`],

In my approach, I would opt for a slight variation by utilizing the forEach method on the array of data rather than a traditional for loop:

function gng(a, b) {
  var c = a / b;
  return c;
}

var tbl = document.createElement('table'),
  dataArray = [
    ["1", "red", ' <input value="' + gng(9,5) + '">'],
    ["2", "white", ' <input value="' + gng(3,5) + '">'],
    ["3", "black", ' <input value="' + gng(4,5) + '">'],
    ["4", "green", ' <input value="' + gng(1,5) + '">'],
    ["5", "gray", ' <input value="' + gng(2,5) + '">']
  ];

dataArray.forEach(function (row) {
  var tr = document.createElement('tr');
  row.forEach(function (data) {
    var td = document.createElement('td');
    td.innerHTML = data;
    tr.appendChild(td);
  });
  tbl.appendChild(tr);
});

document.getElementById('yeni').appendChild(tbl);
<div id="yeni" style="position: absolute; top: 50px; left: 30px; width: 700px; height: 400px; "> </div>

This alternative method simplifies the code, enhances readability, and improves maintainability for future adjustments as there's no longer a manual requirement to update column and row counts if the data array changes.

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

How to trigger an Angular JS route without loading a view

Could someone help me with calling the /auth/logout url to get redirected after a session is deleted? app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/auth/logout',{ controller:'AuthLo ...

Is there a way to selectively display only the first 100 lines using console.log()?

Is there a console.log equivalent of .head() in JavaScript? I need to display only the first 100 lines of a response on my terminal without the top part being cut off due to the entire object being printed. Any suggestions on how to achieve this? ...

Is it possible for the scroll event to be triggered while scrolling only when a div element is used?

While utilizing window.onscroll to track scroll events during scrolling, I noticed that in certain Android devices the scroll event is only triggered after the scroll has completed. However, when monitoring scroll events within a specific div element, it ...

Apply a unique design to a class by clicking on a button

There are 3 identical boxes with the same classes and a button: function changeColorAndAddPadding() { /* ??? */ } .box { border: 1px solid; display: inline; } <button onclick="changeColorAndAddPadding();">Click Here</button> <d ...

Loop through items in a list using Angular.js and display each item within an <

I am facing an issue where the model returned from the server contains html tags instead of plain text, such as b tag or i tag. When I use ng-repeat to create a list based on this model, the html is displayed as pure text. Is there a filter or directive av ...

javascript while loop not functioning properly

Can someone assist me with troubleshooting this while loop issue? <script type="text/javascript"> var num = window.prompt("Please enter a score"); var sum, average; var count=0; while (num > 0) { sum += num; ...

Obtaining the final character of a string in javascript

I need assistance with a JavaScript issue where I am trying to extract the last digit from a string. Here is the code I am using: var idval = focused.id; var lastChar1 = idval.substr(idval.length - 1); For example, if the id name is idval5, the code corr ...

"Must not be currently employed" when using window.open in a basic React application

Let me share a simplified version of the webapp I'm currently developing. Whenever I run into an Uncaught Error: Should not already be working. while executing the window.open(...) line in the following code snippet: const sleep = milliseconds => ...

Is there a way to capture and monitor all page traffic within a scrollable website using playwright?

Here is the code I am using: import { firefox } from 'playwright'; // domain let domain = 'https://www.reddit.com/' // create a new page const page = await browser.newPage(); // set routes await page.route('**', async route = ...

Generate a combined string from a PHP function

While working with PHP, I encountered a situation where I needed to concatenate values stored in an array multiple times. To address this, I created a function specifically for carrying out the concatenation process whenever required. However, I noticed th ...

Tips for grouping data by multiple fields in mongodb

Is there a way to aggregate data by two fields and have the grouping done in a nested manner? The current method I use for grouping is as follows: var query = [ { '$group': { '_id': { 'employee': '$employee&a ...

The order in which Javascript executes when using conditional if statements

As a newcomer in this environment, I humbly ask for forgiveness for any lack of knowledge. My current project involves creating a family feud game for personal use using node.js and express as the server with socket.io handling communication between clie ...

Execute the function when the observable is subscribed to

I'm currently working on creating a custom component that can interact with an observable passed in through an input. The goal is to show/hide elements based on the state of the observable. Here's what I have in mind: @Input() observable: Observ ...

Arrange a collection of objects based on the value of a particular key

In my current dataset, I have an array of objects with 12 indexes, each containing 2 values. The keys 'months' and 'year' are included in each index. 'Months' is a sub-array, while 'year' is currently stored as a str ...

Every time I hit the refresh button, I find myself forcefully logged out

After switching from using localStorage to cookies in my React JS web app, I am experiencing an issue where I get logged out whenever I refresh the page. Even though the cookies are still stored in the browser, the authentication process seems to be failin ...

Moodle version 3.0 is experiencing issues with loading CSS and Javascript due to compatibility issues with NGINX requests not matching the actual paths

Here is my current configuration: Operating System: Ubuntu 14.04 Web Server: Nginx 1.4.6 PHP Version: 5.5.9 Moodle Version: 3.0 After successfully installing Moodle 3.0 through the browser, none of the CSS or JavaScript files are loading. The error logs ...

Tips for implementing HTTP subscription with RxJS map to retrieve two arrays of objects

I have received two arrays of objects from the backend. Here is the structure of the data: Array(object1): [{"record_id":"1", "local_TimeStamp":"16:00:00", "country":"USA"}, {"record_id":"2", "local_TimeStamp":"17:00:00", "country":"Japan"}, {"record_id ...

Tips on accessing PDF files in a new window and downloading them within a blank pop-up screen

I am currently attempting to replicate a specific situation in order to debug an issue. In this scenario, I need to click on a date that will open a new pop-up window. However, the window is blank and a PDF file is downloaded within that window. Unfortunat ...

Error encountered when attempting to insert data into database due to incompatible data types

I am experiencing an issue with Vue multiselect. I am trying to save the id of selected options in a database, but it seems that I am encountering an error related to Array to string conversion. I have declared both site_id and administrator in fillables. ...

Guide for extracting the button click text using selenium and node js, illustrated in the image

Attempting to extract the text displayed upon button click, as seen in the image. Below is the code I have used after accessing the website, however it failed to retrieve the text. //*[@class='']//*[text()=''] ...