Assign a value to an element based on a specific attribute value

I'm working with the following element

<input type="text" size="4" name="nightly" value="-1">

My goal is to update the value to 15.9 specifically when name="nightly"

Here's what I've attempted so far:

document.getElementsByName('name')['nightly'].setAttribute('value', '15.9');

But unfortunately, this results in an error message:

TypeError: undefined is not an object (evaluating 'document.getElementsByName('name')['nightly'].setAttribute')

Answer №1

document.getElementsByName() function returns an array of all elements that match a specific name.

In the case where only one element is retrieved, you can use this method:

document.getElementsByName('nightly')[0].setAttribute('value', '15.9'); //the index 0 indicates the first and only element in the array.

For situations with multiple elements, you can iterate through the array like so:

var elements = document.getElementsByName('nightly');

for (i = 0; i < elements.length; i++)
{
    elements[i].setAttribute('value', '15.9');
}

Answer №2

var dailyRates = document.getElementsByName('nightly');
dailyRates.forEach(function(rate) {
  rate.value = 15.9;
});

I trust this meets your requirements.

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

What is the proper way to invoke a function in the code-behind using JavaScript?

I need to invoke a function in the code behind from JavaScript Button : <button class = "btn btn-outline btn-danger dim" type = "button" onclick = "confirmDelete ()"> <i class = "fa fa-trash"> </i> ...

Unique syntax using markdown-react

I want to customize the syntax highlighting in react-markdown. Specifically, I would like to change the color of text inside {{ }} to blue while still maintaining the correct formatting for other elements, such as ## Header {{ }} import React from " ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

Is VueJS2 using the computed property/method to modify Vue data?

My form in Vue is almost complete, but I'm facing an issue with an array that seems to be affecting my Vue.data object directly. Here's the situation: In my code, I have a method called getParams() which returns an object containing all the data ...

Checking the types of arrays does not function properly within nested objects

let example: number[] = [1, 2, 3, 'a'] // this code block correctly fails due to an incorrect value type let example2 = { demo: 1, items: <number[]> ['a', 'b'], // this code block also correctly fails because of ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Utilize data obtained from an ajax request located in a separate file, then apply it within a local function

Seeking assistance in navigating me towards the right path or identifying my errors. Pardon if my explanation is unclear, please be gentle! Currently, I am engaged in developing a function that executes an ajax call with a dynamically generated URL. The o ...

Which HTML element does each script correspond to?

Are there any methods to identify the script used in certain HTML elements? For instance, if I wish to determine the script responsible for creating a drop-down menu, I can locate the HTML and CSS for the menu but not the JavaScript (or other scripts). I ...

Using Firebase Realtime Database, this React dropdown menu is populated with options in real-time. Combining the features

I'm currently facing an issue with a dropdown that is supposed to loop through data fetched from the Firebase realtime database. The goal is to assign a selected value to a Formik form for saving it to another object in the database. In my database, ...

Is there a way to determine the negative horizontal shift of text within an HTML input element when it exceeds the horizontal boundaries?

On my website, I have a standard HTML input field for text input. To track the horizontal position of a specific word continuously, I have implemented a method using an invisible <span> element to display the content of the input field and then utili ...

Utilizing a dynamically created Stripe checkout button

Currently, I am attempting to integrate a checkout button from the Stripe Dashboard into my VueJS Project. I have a feeling that I might not be approaching this in the correct manner, so if you have any advice, I would greatly appreciate it. In order to ...

Obtaining specific data from the forEach iteration, post-click event with JavaScript

Trying to access the value from a Tree-structured Array of Objects stored in Local Storage, Created a function that retrieves values from local storage using forEach and displays them on the screen. Clicking on the Yes/No button triggers the same functio ...

Why is my custom Vuelidate validator not receiving the value from the component where it is being called?

On my registration page, I implemented a custom validator to ensure that the password meets specific criteria such as being at least 12 characters long and containing at least one digit. However, I encountered an issue where the custom validator was not r ...

Performing asynchronous operations in React with axios using loops

On the backend, I have a socket set up to handle continuous requests from the server. Now, my goal is to send requests to the backend API continuously until a stop button is clicked. Using a loop for this task is considered bad practice as it never checks ...

Sending back JSON arrays containing Date data types for Google Charts

One of my challenges involves using a 'Timelines' chart from Google Charts, which requires a JavaScript Date type when populating data. Here is my initial code snippet: var container = document.getElementById('divChart1'); var chart = ...

Steps to modify the servletRequest's content length within a filter

My main objective is to secure the POST body requests sent from my web application to my service by encrypting them. This encryption process takes place within a filter in my system. However, I've encountered an issue related to content length. When ...

The error code 405 (Method Not Allowed) occurs in Ajax when the action field is empty or identical to the current page

Special thanks to @abc123 for sharing the code below in one of their posts: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <form id="formoid" a ...

loading times of Bootstrap-select are slow when used in multiples

I am facing performance issues on my website when I try to include more than 20 select options. The jQuery execution slows down significantly and there is a stop/continue alert, taking minutes to load. Is there any way to optimize the code for faster loadi ...

Unable to run the JSON.parse() function while using the 1.10.2 version of jquery.min.js

Has anyone else encountered a situation where using JSON.parse() to parse the PHP array return only works when applying 1.3.2/jquery.min.js and not 1.10.2/jquery.min.js? If so, what solution did you find? PHP array return $returnArray['vercode' ...

Strangely peculiar glitch found in browsers built on the Chromium platform

During a school assignment, I'm attempting to adjust the width of a button using Javascript. Below is my code: const button = document.querySelector("button"); button.addEventListener("click", () => { console.log(button.offsetWidth); butto ...