Keep the true number hidden in the JavaScript array

Today while working on a script, I encountered an issue when trying to test it. The script was not returning the correct value - instead, it was showing [object Object] which was not the expected output. You can see a screenshot of the problem here. To resolve this, I need to click on "Edit" next to Google or Yahoo. When I try to change the value from Checked[Item] to Checker[Name], it only displays undefined.

This is the HTML code:

<!DOCTYPE html>
<html>

<head>

    <title>SSL Checker</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script type="text/javascript" src="js/script.js"></script>
    <script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>

<body onLoad="start()">
    <div id="title">
        <h1>SSL Checker</h1>
    </div>
    <div id="data">
        <form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
            <input type="text" id="add-name" placeholder="Name"></input>
            <input type="text" id="add-link" placeholder="Link"></input>
            <input type="submit" value="Add">
        </form>

        <div id="edit" role="aria-hidden">
            <form action="javascript:void(0);" method="POST" id="saveEdit">
                <input type="text" id="edit-name">
                <input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">&#10006;</a>
            </form>
        </div>
        <p id="counter"></p>
    </div>
    <div id="table">
        <table style="overflow-x:auto;">
            <tr>
                <th>Sites:</th>
            </tr>
            <tbody id="urls">
            </tbody>
        </table>
    </div>
</body>


</html>

This is the JS code:

function start() {
    var SSL = new function() {
        //List urls to check
        this.el = document.getElementById('urls');
        this.Count = function(data) {
            var el = document.getElementById('counter');
            var name = 'url';

            if (data) {
                if (data > 1) {
                    name = 'urls';
                }
                el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
            } else {
                el.innerHTML = 'No ' + name;
            }
        };
        //Buttons configuration
        this.FetchAll = function() {
            var data = '';

            if (Checker.length > 0) {
                for (i = 0; i < Checker.length; i++) {
                    data += '<tr>';
                    data += '<td><a href="http://' + Checker[i].url + '">' + Checker[i].name + '</a></td>';
                    data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
                    data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
                    data += '</tr>';

                }
            }

            this.Count(Checker.length);
            return this.el.innerHTML = data;
        };
        //Add name
        this.Add = function() {
            el = document.getElementById('add-name');
            el1 = document.getElementById('add-link')
            var url = el.value;
            var url1 = el1.value;
            if (url) {
                if (url) Checker.push({
                    "name": url,
                    "url": url1
                })
                el.value = '';
                this.FetchAll();
            }
        }

        //Edit
        this.Edit = function(item) {
            var el = document.getElementById('edit-name');
            el.value = Checker[item];
            document.getElementById('edit').style.display = 'block';
            self = this;
            document.getElementById('saveEdit').onsubmit = function() {
                var url = el.value;
                if (url) {
                    self.Checker.splice(item, 1, name.trim());
                    self.FetchAll();
                    CloseInput();
                }
            }
        };
        //Delete
        this.Delete = function(item) {
            Checker.splice(item, 1);
            this.FetchAll();
        };

    };

    SSL.FetchAll();

    function CloseInput() {
        document.getElementById('edit').style.display = 'none';
    }
    window.CloseInput = CloseInput;
    window.SSL = SSL;
}

The JSON file contains the following data:

var Checker = [{
        name:"Google",
        url: "google.es",
    },
    {
        name:"Yahoo",
        url: "yahoo.com",
    }
]

Answer №1

Create additional input tags for every attribute of the Checker's objects.

<input type="text" id="edit-name">
<input type="text" id="edit-url">

Assign values to each input field individually:

var el = document.getElementById('edit-name');
el.value = Checker[item].name;
var el2 = document.getElementById('edit-url');
el2.value = Checker[item].url;

Here is the final working code snippet:

var Checker = [{
    name: "Google",
    url: "google.es",
  },
  {
    name: "Yahoo",
    url: "yahoo.com",
  }
]

document.getElementById('edit').style.display = 'none';

function start() {
  var SSL = new function() {
    //List urls to check
    this.el = document.getElementById('urls');
    this.Count = function(data) {
      var el = document.getElementById('counter');
      var name = 'url';

      if (data) {
        if (data > 1) {
          name = 'urls';
        }
        el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
      } else {
        el.innerHTML = 'No ' + name;
      }
    };
    //Buttons configuration
    this.FetchAll = function() {
      var data = '';

      if (Checker.length > 0) {
        for (i = 0; i < Checker.length; i++) {
          data += '<tr>';
          data += '<td><a href="http://' + Checker[i].url + '">' + Checker[i].name + '</a></td>';
          data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
          data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
          data += '</tr>';

        }
      }

      this.Count(Checker.length);
      return this.el.innerHTML = data;
    };
    //Add name
    this.Add = function() {
      el = document.getElementById('add-name');
      el1 = document.getElementById('add-link')
      var url = el.value;
      var url1 = el1.value;
      if (url) {
        if (url) Checker.push({
          "name": url,
          "url": url1
        })
        el.value = '';
        this.FetchAll();
      }
    }

    //Edit
    this.Edit = function(item) {
      var el = document.getElementById('edit-name');
      el.value = Checker[item].name;
      var el2 = document.getElementById('edit-url');
      el2.value = Checker[item].url;
      document.getElementById('edit').style.display = 'block';
      self = this;

      document.getElementById('saveEdit').onsubmit = function() {
        var url = el2.value;
        var name = el.value;
        if (url && name) {
          Checker[item].name = name;
          Checker[item].url = url;
          self.FetchAll();
          CloseInput();
        }
      }
    };
    //Delete
    this.Delete = function(item) {
      Checker.splice(item, 1);
      this.FetchAll();
    };

  };

  SSL.FetchAll();

  function CloseInput() {
    document.getElementById('edit').style.display = 'none';
  }
  window.CloseInput = CloseInput;
  window.SSL = SSL;
}
<html>

<head>

  <title>SSL Checker</title>

</head>

<body onLoad="start()">
  <div id="title">
    <h1>SSL Checker</h1>
  </div>
  <div id="data">
    <form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
      <input type="text" id="add-name" placeholder="Name"></input>
      <input type="text" id="add-link" placeholder="Link"></input>
      <input type="submit" value="Add">
    </form>

    <div id="edit" role="aria-hidden">
      <form action="javascript:void(0);" method="POST" id="saveEdit">
        <input type="text" id="edit-name">
        <input type="text" id="edit-url">
        <input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">&#10006;</a>
      </form>
    </div>
    <p id="counter"></p>
  </div>
  <div id="table">
    <table style="overflow-x:auto;">
      <tr>
        <th>Sites:</th>
      </tr>
      <tbody id="urls">
      </tbody>
    </table>
  </div>
</body>


</html>

Answer №2

The reason you are seeing the output as [object Object] is because the method Object.toString() specifically returns [object Object].

If you want to customize the representation of your object, you can modify the section in your SSL.Edit() method where you assign el.value = Checker[item]. You could change it to something like:

  • el.value = Checker[item].name; // Displaying the name
  • el.value = Checker[item].url; // Displaying the URL
  • el.value = Checker[item].url + ' ' + Checker[item].url; // Displaying both

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

Hover over the sprites using the "spritely" plugin to see the magic unfold

I'm looking to initiate an animation when the mouse hovers over a sprite and have it stop when the mouse moves away. After exploring various solutions, I found one that seemed promising: Why does jQuery spritely animation play an extra frame on secon ...

Navigate to a different webpage: Node.js

I've tried numerous solutions listed here, but being new to node.js, I seem to be missing a crucial part in my code. Can someone please assist me in identifying and resolving the issue? When the login button is clicked, my objective is to redirect the ...

Safari on PC and iPhone does not show jpg images

My website is functioning properly on Internet Explorer, Firefox, and Chrome with all images displaying correctly. However, Safari on both PC and iPhone are not showing all of the images. Even after clearing the cache in Safari and reloading the page, some ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...

"Instant Elementor offers seamless CSS transitions for an enhanced user experience

UPDATE: Issue resolved, discovered that Elementor was overriding certain styles. Please refer to my solution below. I'm attempting to add animation to a simple max-height property of a div, but the transition isn't working as expected. It transi ...

I have a JSON object with a nested "src" value that I want to display on my webpage using Vue. How can I target and select this specific value?

I am currently working with an API and attempting to access a nested object within the JSON data named "Species Illustration Photo". Inside this object is an "img" property with the source link. How can I display this nested img source in my HTML using Vue ...

triggering the onsen's setMainPage function when clicked using a variable from ng-repeat loop

I need help customizing my Onsen UI splitView app to dynamically set the main page based on a variable received from a clicked item in a list generated by ng-repeat. After researching ng-repeat and ng-click, I am still unable to achieve the desired outcom ...

Is it feasible to maintain a variable as a reference across views while utilizing ng-view?

I am facing a unique challenge: I have a webpage with two tabs that need to utilize ng-view from AngularJS. The twist is that both tabs must share the same variable, similar to referencing a variable in C# using the "ref" keyword. If you want to see an ex ...

Uh-oh: create-react-app installation has been canceled

As per the guidelines provided in Reactjs documentation: To start a new project, you must have Node version >= 8.10 and npm version >= 5.6 installed on your system. Use the following command to create a project: npx create-react-app my-app My envir ...

PWA JavaScript struggling with GPS geolocation coordinates

I am experiencing issues with the GPS coordinates being stuck when using geolocation in a Progressive Web App (PWA). Sometimes, the coordinates get stuck at the previous location, even if the user has moved since then. I suspect that this is due to the GP ...

The use of Array.push() within an $http.get() function in AngularJs results in an array with unexpected

I'm stuck trying to debug my code, particularly because it seems to be related to a javascript issue. The problem arises when I attempt to load a local txt file using $http.get (is there another method that might work better?). The goal is to store t ...

When making an Ajax request, the response is received successfully, however, the success, complete, and error

I am attempting to retrieve SQL results from a database using an AJAX call and display them on another PHP page. Here is my AJAX call code: function newfunc(){ start += 10; var params = parseURLParams(document.URL); var datastring = "nextStart="+start+"&a ...

The Axios GET method retrieves a response in the form of a string that represents an object

I have developed a function that triggers an axios Request. I am working with typescript and I am avoiding the use of any for defining return data types of both the function and the axios request itself. The issue arises when the returned object contains ...

Lag in responsiveness of iOS devices when using html5 applications

My HTML5 video app includes a combination of video, a JavaScript swipable playlist, and other animated overlays. When using the app on iOS, the performance of playlist swiping and overlay animations is great upon initial load. However, after playing a vid ...

Automated Quote Assignment in Fact Array: A Guide to Automatically Tagging Quotes to Text Lines

Greetings everyone! I recently started delving into android studio and am currently working on an app that showcases interesting facts. Everything is running smoothly, but I have a query - Is there a way to automate the process of adding quotes to each fac ...

Troubleshooting issues with Angular 8 component testing using karma leads to failure

As I begin testing my component, my first goal is to verify that the ngOnInit function correctly calls the required services. agreement.component.ts: constructor(private agreementService: AgreementService, private operatorService: Operato ...

Ensuring the safety of JavaScript requests made to a Web Service

In my project, there is a page that triggers a JSon script when a button is clicked. This script interacts with a web service. To ensure security, the code behind the page generates a script containing an object with a unique code. This code is then added ...

Yet Another Simple JavaScript Inquiry

Hello, I am facing an issue with a jquery .post as it is not properly outputting the desired result. Below is the code snippet: jQuery(document).ready(function($){ $('#project-for-support-ticket').change(function(){ //Pass The value sele ...

Unable to dynamically attach a class in Vue.js

I have exhausted all possible variations of this issue. I meticulously followed the official Vue guides, consulted numerous stack overflow posts, and went through various tutorials. I experimented with different syntaxes, quotations, array structures, and ...

Trouble with importing React JSX from a separate file when working with Typescript

This problem bears some resemblance to How to import React JSX correctly from a separate file in Typescript 1.6. Everything seems to be working smoothly when all the code is contained within a single file. However, as soon as I move the component to anoth ...