Updating input field value with JavaScript

I am working with two textboxes

<input id='random_value' name='random_name' value='First'
<input id='random_value' name='random_name' value=''

My challenge is to replace the value of a textbox that currently has 'First' with 'Second', without using either the textbox id or name. Do you think this is achievable?

Answer №1

This custom function is specifically designed to update the content within all input elements from "First" to "Second":

function replaceTextContent() {
    var elements = document.getElementsByTagName("INPUT");
    for(var index = 0, limit = elements.length; index < limit; index++) {
        if(elements[index].value == "First")
            elements[index].value = "Second";
    }
}

Answer №2

Here is a way to make selections:

var input = document.getElementsByTagName("INPUT");
var j = 0;

for (var i = 0; i < input.length; i++) {
  if (input[i].type == "text") {
      if (input[i].value == "First") {
         input[i].value == "Second"
      }
  }
}

If you know the index of the element in the DOM, you can do this directly:

<HTML>    
<FORM>

   <input id='random_value' name='random_name' value='First'/>
   <input id='random_value' name='random_name' value=''/>
    </FORM>
</HTML>

You can set the value like this:

document.forms[0].elements[0].value=document.forms[0].elements[1].value;

If the form is first and the text box is the first element of the form, otherwise you can specify the index instead.

If you don't know the index, you can loop through all elements, check for the value "First," and make changes accordingly.

Answer №3

In order to achieve the desired outcome, you will need to create a loop.

 let elements = document.getElementsByTagName('input');
 let index = 0;
 for(index = 0; index < elements.length; index++){
     if(elements[index].value == "First"){
        elements[index].value = "Second";
     }
 }

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 best way to execute a randomly chosen function in JavaScript?

I need help running a random function, but I'm struggling to get it right. Here's what I have so far: <script> function randomFrom(array) { return array[Math.floor(Math.random() * array.length)]; } function randomchords(){ randomFrom ...

In JavaScript, how is the symbol "." referred to as?

While I am familiar with its purpose and the language terminology, could you please provide the official name for the period/dot used in Javascript/jQuery? Appreciate your help! ...

Unable to display the column data labels in Highcharts due to the incorrect formatting being presented

I'm having trouble displaying the datetime format at the top of a column in my chart. Although the tooltip shows the correct data when hovering over the columns, the labels are not formatted properly. Received output - 86340000 Expected output - 23: ...

What is the correct way to successfully implement this SQL query that relies on promises?

Currently, I am using MySQL2 to establish a connection between my Node.js application and a MySQL Database. However, I am facing difficulties in implementing promise-based prepared statements as I struggle to create a function that can either successfully ...

Utilize Javascript to acquire the AspNet.ApplicationCookie

I'm completely clueless if this is even doable, but I have to inquire. Is there a method to retrieve the AspNet.ApplicationCookie from Cookies? I've attempted the following: `$.cookie('.AspNet.ApplicationCookie');` `document.cookie;` ...

Cookies are strangely absent from the ajax call to the web api - a puzzling issue indeed for Web Api users

Hello, here is the code I'm working with using Ajax: function GetCurrentUserId() { return $.ajax({ type: "GET", url: rootUrl + '/api/Common/CurrentDateAndUser', dataType: 'json', ...

Choose a unique text color

Having trouble with my HTML select form and modifying text color for specific options. In the provided example, I changed the color for the Tuesday option, but it only shows up when scrolling through the options. How can I make the color change visible for ...

What is the best way to trigger a modal on Bootstrap using a JavaScript/jQuery function?

I encountered an issue while attempting to call a bootstrap modal using a simple button or link, which may be due to a conflict with my select2 plugin (although I am uncertain). I tried appending the button to the select2 dropdown but it doesn't seem ...

Using multiple html files with ui-router's ui-view feature

Is it possible to create a complex UI using multiple HTML files with ui-view in AngularJS? I am trying to achieve a layout similar to this: I attempted to implement something on Plunker, but it seems like I'm struggling to grasp the underlying concep ...

What is the most effective way to modify a specific field within a MongoDB document - utilizing either the update or patch hook in FeathersJS?

I am currently working on updating a single field in a MongoDB document, and I am unsure whether to use the patch or update method within the Feathers framework. Can someone provide an example of how to do this? const { authenticate } = require('feat ...

3 Methods for Implementing a Floating Header, Main Content, and Sidebar with Responsive Design

I am following a mobile-first approach with 3 containers that need to be displayed in 3 different layouts as shown in the image below: https://i.sstatic.net/UjKNH.png The closest CSS implementation I have achieved so far is this: HTML: <header>.. ...

Modify a single parameter of an element in a Map

Imagine I have a map data type exampleMap: Map<string, any> The key in the map is always a string, and the corresponding value is an object. This object might look like this: { name: 'sampleName', age: 30} Now, let's say the user se ...

Encountering an error with requireJS: "Unknown provider $routeProvider with AngularJS 1.2.9 ngRoute"

Currently, I am utilizing angularJS-1.2.9 and angular-route-1.2.9 to configure routes for my application. Additionally, I have integrated requireJS as the dependency loader to modularize the code. Despite adding the ngRoute dependency into the AngularJS co ...

After signing out and logging back in, data fails to display - ReactJS

I am encountering difficulties with the login/logout process and displaying data in a form. When I restart my server and log in without logging out, everything works fine and the data appears in the form. However, if I log in, then log out, and log back in ...

Error encountered: AngularJS routes causing 500 internal server error

I am struggling with organizing my directory structure. Here is how it currently looks - -project -public -app -app.js ( angular app module ) -server -server.js ( node root js file ) -includes -layout.jade - ...

Exploring First-Person Shooter Rotation with THREE.JS

I recently attempted to create a rotation system for a First Person Shooter game using THREE.JS. However, I encountered a strange issue where the camera would pause momentarily before returning, especially at certain rotations. When checking the rotation ...

Guide on Resolving AJAX Filtered Product List Issue with Missing Images in Django Ecommerce Website

I'm facing an issue while implementing filter functionality in my e-commerce project. When I utilized AJAX to generate a filtered product list, all the products are visible but the images aren't showing up. urls.py: urlpatterns = [ path(&apo ...

Is there an issue with my JavaScript append method?

Within the following method, an object named o gets appended to a list of objects called qs. The section that is commented out seems to be causing issues, while the uncommented section is functional. What could possibly be wrong with the commented part? on ...

Why is the result of this specific JavaScript code a string?

let x = 2, y = x = typeof y; console.log(x); // >> 'string' Could you explain why the value of x ends up being a string in this code snippet? ...

Sorting WordPress entries by nearby locations

I have WordPress posts that are being displayed on a Google Map. The posts are pulling data from a custom post field that contains the latlng value, where latitude and longitude are combined into one. Additionally, the map shows the user's location u ...