Accessing a span element using an eval function

I have a function that accesses an input element and updates its value using the following line of code:

eval('document.forms[0].telephone').value = $telephone[$i];

Now, I need to transfer this value to a span, but I'm having trouble referencing it correctly. The current input has both a name and an id of "country", and I suspect that my eval() is targeting the name.

The span does not have a name, but instead uses a class called tel-prefix.

I've attempted various approaches to reference it (and different combinations), but none seem to be working:

eval('document.forms[0].tel-prefix').value = $telephone[$i];
eval('.tel-prefix').value = $telephone[$i];
eval('.tel-prefix').text= $telephone[$i];
$('.tel-prefix').value = $telephone[$i];
$('.tel-prefix').value($telephone[$i]);

Is there a way for my eval() to update the value of my span?

Complete JS Code

$telephone = new Array(4)
$telephone  [0] = "+93"
...
$telephone  [246] = "+260"
$telephone  [247] = "+263"

function getTelephone($selectedIndex) {
    $selectBox = document.forms[0].spch_country;
    if ($selectBox.options[$selectedIndex].value != 'none') {
        for ($j = 0, $i = $selectedIndex; $i < $selectedIndex + 1; $j++, $i++) {
            eval('document.forms[0].tel-prefix').value = $telephone[$i];
        }
    }
}

Answer №1

Initially, the use of eval in this context is unnecessary, as there is no need for that type of evaluation. The original code should have simply been:

document.forms[0].telephone.value = $telephone[$i];

The utilization of the eval function poses security risks like potential cross-site scripting attacks. Even when dealing with dynamic field names, accessing elements using eval is never essential; they can be accessed by name without employing eval. For instance:

var formNumber = 0;
var fieldName = "telephone";
document.forms[formNumber][fieldName].value = $telephone[$i];

Regarding the span; in modern browsers, you can utilize the querySelector method to locate it using the class name. After which, you can set the content using the innerHTML property:

document.querySelector('.tel-prefix').innerHTML = $telephone[$i];

To ensure compatibility with older browsers, adding an id to the span (e.g., id="telPrefix") would be beneficial. This way, you can employ the getElementById method:

document.getElementById('telPrefix').innerHTML = $telephone[$i];

While locating the element using the class name is feasible, in browsers lacking support for the querySelector method, you may need to iterate through all elements on the page to find it.

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

Access a webpage whose URL has been dynamically assigned using JavaScript

I have a website that consists of a single page and features four tabs. Whenever a tab is clicked, it displays the corresponding content in a div while hiding the other three divs along with their respective content. To ensure a smooth user experience, I u ...

Is it possible to incorporate a variable into an object?

If you are wondering whether it is possible to utilize a variable in the following scenario, the reason for my inquiry is connected to the potential of utilizing an input element to dynamically modify the variable: var str = "pineapples" var cost = { pine ...

Using the Object.assign technique will modify the original object's properties in JavaScript

Recently delving into ReactJS, I stumbled upon an interesting revelation regarding the Object.assign() method: const B = { k1: 'b', k2: 'bb', treedata: [{ children: ['g'] }] } var A = Object.assign( ...

AngularJS application: the button requires two clicks to activate

In my attempt to develop a simple CRUD app using AngularJS, I encountered an issue. The initial step involves clicking a button that fetches data from a REST API and populates an array. This array is then iterated using ng-repeat to generate Bootstrap card ...

Discover the world of Google Chrome Apps with the power of chrome.storage.local

While building an application, I encountered a perplexing issue that I need help with: The task involves reading a JSON file and storing its content in localStorage using chrome.storage.local in a Chrome app. Here is a snippet from the JSON file: { "s ...

The component you are trying to import requires the use of useState, which is only compatible with a Client Component. However, none of the parent components have been designated with the "use client" tag

I encountered an issue with the code snippet below in my Next.js app directory when utilizing useState: When trying to import a component that requires useState, I received this error message. It seems that the parent components are marked as Server Co ...

The Vue.js route is not aligning with its defined path, causing a mismatch

Attempting to develop a Vue SPA app, but encountering an issue with the routes not matching what was defined in the router. Despite all configurations seemingly correct, there is confusion as to why this discrepancy exists. What element might be overlooked ...

Closing WebSocket connection after sending data

I came across an interesting blog post titled Experimenting with Node.js and decided to try setting it up on my own using the author's provided gist. Unfortunately, I encountered some issues. After further investigation, I discovered that even though ...

Error: FileReader is not defined in Node.js (Nest.js) environment

I am working on converting my image to base64 using a custom function. However, when I try to execute the code, I encounter an error message stating ReferenceError: FileReader is not defined. This error has left me puzzled and unsure of its cause. Below i ...

What steps can be taken to resolve an error encountered when attempting a dynamic data POST request from the body

Whenever I attempt the post method to fetch data on Postman and store it in a local MongoDB database, I encounter an error. The error message indicates a bad request with a status code of 400. *The following is app.js: var express = require('express& ...

The Vue2 @click event does not function properly when using v-html within a different component

I currently have a sign up form that includes an Alert component for displaying any errors. One of the conditions may prompt a message saying "You already have an account, click here to log in". The error messages are passed as props to the "Alert" compon ...

Exporting a Component with React can be done in two ways: named exports and

There's a common syntax I've come across in various files: import React, {Component} from react; While I grasp the concept of named exports and default exports individually, I'm uncertain about how React manages this when exporting its cod ...

The raycaster is experiencing issues when used with multiple cameras in the Three.js library

I am currently developing an application similar to the threeJs editor. In this project, I have implemented four different cameras, each with unique names and positions. Here is an example of one of the cameras: cameras['home'] = new THREE.Combi ...

Adding an await tag to dispatch causes issues with performing a react state update on an unmounted component

I recently added an await tag to a redux dispatch and now I am encountering the following error message: index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your applica ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...

Is there a way to obtain the "rotated" coordinates of a mouse click within a canvas element?

Exploring New Features Within my image editing software, there is a canvas where users can draw shapes. These shapes are sent to a server and added to an XML file, which is then returned to the client for display. Now, I am looking to enhance the program ...

Tips for showcasing overflowing text in a menu list by rotating the item text

Imagine you have a TextMenuItem component, using MenuItem from the Material-UI library, that is part of a chain consisting of DropDownSearch > SimpleListMenu > FixedSizeList > TextMenuItem. In simple terms, this creates a searchable dropdown eleme ...

Angular is known for sending only the fields that have changed to the update method

I need help with optimizing my save method. When a user clicks SAVE, I only want to send the fields that have been changed instead of all 50+ fields on the page. This will reduce the amount of data being sent every time. Api.Admin.update({ obsoleteDat ...

Issue with setTimeout function when used in conjunction with an ajax call

Currently, I am developing a quiz portal where questions are organized in modules. Each module consists of 5 questions: the first 4 are text-based, and the 5th is an image-based question. Upon registering through register.php, users are directed to index. ...

Enhance the app.get response by integrating data fetched from an http.get request

Currently, I am utilizing express and passing the path as a URL parameter. app.get("/download", function (req, res) { var location; var options = { host: 'example.com', port: 80, path: req.query.url.replace(/ /g, ...