Accessing an HTML DOM element and assigning it to the value of an input tag

One of the elements on my webpage has the unique identifier last_name. I am trying to extract its value and pass it to an input tag.

My attempt at achieving this is shown below, but it does not work as intended.

<input type="hidden" name="lastName" value=document.getElementById("last_name").value>

Is there a method to accomplish this task?

This action is not just limited to page load.

To elaborate, I have multiple textboxes arranged together in a form.

Subsequently, I have another form containing a button. When the user clicks the button, I want the values of my input tags to be the current entries in the textboxes.

EDIT: My issue has been resolved! I had to eliminate the "value" attribute from the input tags, then include an "onclick" attribute to my button, and finally utilize the provided javascript codes to achieve the desired functionality.

Answer №1

Just for page loading:

 <!DOCTYPE html>
    <html>

    <head>
        <!-- Include your JQuery library here -->
        <script>
           $(function(){
              $('#lastName').val($('#last_name').val());
           });
        </script>
    </head>

    <body> 
        <input type="text" id="last_name" value="123"> 
        <input type="hidden" name="lastName" value="">
    </body>

</html> 

For button click event:

 <!DOCTYPE html>
    <html>

    <head>
        <!-- Include your JQuery library here -->

        <script>
           $(function(){
              $('#btn-save').on('click', function() {  
                  $('#lastName').val($('#last_name').val());
                  // additional tasks may go here
                  return false;
              }
           });
        </script>
    </head>

    <body> 
        <input type="text" id="last_name" value="123"> 
        <input type="hidden" name="lastName" value="">
        <button id="btn-save">Save</button>
    </body>

</html>  

No jQuery approach:

        <script>
            window.onload = function(){
               var src = getElementById('last_name');
               var dst = getElementById('lastName');
               dst.value = stc.value;
           }
        </script>

Answer №2

Give this a shot:

let lastNameInput = document.getElementById("last_name");
let userInput = document.getElementById("inputId");
userInput.value = lastNameInput.value;

Answer №3

Below is a sample code snippet for HTML:

<input type="hidden" name="lastName" id='hidLastName' />

Accompanied by the corresponding javascript code:

var hiddenInput = document.getElementById("hidLastName")
   hiddenInput.value =  document.getElementById("last_name").value

Answer №4

To enhance efficiency, consider transferring the logic to a separate .js file or embedding it within a <script></script> element, with the former being the recommended option. An example implementation is demonstrated below:

Add an id attribute to the input that will receive the data:

<input type="hidden" id="lastName" name="lastName">

Include the following code in your .js file:

window.onload = function(){
    var lastNameInput = document.getElementById('lastName');
    var sourceInput = document.getElementById('last_name');
    lastNameInput.value = sourceInput.value;
}    

Answer №5

Check this out: Java Script

<script>
    function updateLastName() {
        document.getElementById("lastname").value = document.getElementById("last_name").value;
    }

</script>

HTML

<input type="text" id="last_name"  onblur="updateLastName()"/>
<input type="hidden" id="lastname" />

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

Floating image positioned between two div elements

Attempting to replicate a specific design using HTML/CSS has been a challenge. I've been struggling to position an image on top of the two divs. I would greatly appreciate any assistance with the design. Here is what I have tried so far: The follo ...

The functionality of Bootstrap toggle ceases to operate properly following an AJAX content update

I am currently using AJAX load to fetch some content on my webpage. I am working with Bootstrap 3 and Bootstrap toggle. When the content is loaded, the Bootstrap 3 content functions properly (the panel-primary panel is clearly visible). However, the Bootst ...

Can the z-index property be applied to the cursor?

Is it possible to control the z-index of the cursor using CSS or Javascript? It seems unlikely, but it would be interesting if it were possible. Imagine having buttons on a webpage and wanting to overlay a semi-transparent image on top of them for a cool ...

Setting the select option in AngularJS with predefined options can be easily achieved with

I am encountering an issue with a select element that has predefined options. Even though the select element is using ng-model, when the model is set to one of the option values, it fails to be selected. Below is the snippet of HTML code: <select clas ...

Is jQuery utilized by the bootstrap-grid system?

Finale: In our current setup, we are utilizing Angular 9, and like many frontend frameworks, there is a preference against incorporating other JavaScript libraries alongside the framework for manipulating the DOM. The Challenge: I am hesitant to include ...

Using HTML5 data attributes as alternative configuration options in a jQuery plugin can present challenges

I am currently in the process of creating my very first jQuery plugin, and I have encountered a challenge when attempting to extend the plugin to support HTML5 data attributes. The idea is for a user to be able to initialize and adjust settings simply by u ...

Modifying shapes and figures in three-dimensional Javascript

I am currently struggling to transform a cube into a sphere in Three.js either after a specific time interval or upon an event click. I have attempted changing the geometry property from BoxGeometry to SphereGeometry with no success. Despite trying some po ...

Exploring the asp.net MVC framework with the integration of HTML5 date input

Currently, I am working on an ASP.NET MVC project using Visual Studio 2013. One of the issues I am encountering is related to a date input field. When I click on the field and focus on it, the automatic HTML5 datepicker does not appear. If I enter the da ...

Utilizing Material UI Grid spacing in ReactJS

I'm encountering an issue with Material UI grid. Whenever I increase the spacing above 0, the Grid does not fit the screen properly and a bottom slider is visible, allowing me to move the page horizontally slightly. Here is the simplified code snippe ...

CSS transforms the entire div, ensuring that all elements within it remain

When I try to rotate a set of divs using the following code: map-grid: -webkit-transform:skewX(-45deg) rotate(15deg) scaleX(1.785) scaleY(.8) translateX(7em) translateY(-4.5em); -moz-transform:skewX(-45deg) rotate(15deg) scaleX(1.785) scaleY(.8) trans ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

What is the process for verifying a Bootstrap form?

I have created a form using Bootstrap (Form component in ReactJS), but when I attempt to click on the submit button without entering any input, the form is still submitted. How can I implement form validation so that it only submits when all input fields a ...

The width and height properties in the element's style are not functioning as expected

let divElement = document.createElement("div"); divElement.style.width = 400; divElement.style.height = 400; divElement.style.backgroundColor = "red"; // num : 1 divElement.innerText = "Hello World "; // num : 2 document.body.append(divElement); // Af ...

Exploring Bootstrap datatables to search through nested table data with Codeigniter

I have implemented a table using bootstrap datatables and successfully enabled search functionality within the table. However, I have also included nested tables within each row of the main table. These nested tables are supposed to be displayed when clic ...

Is the setInterval function in JavaScript only active when the browser is not being used?

I am looking for a way to ensure proper logout when the browser is inactive using the setInterval() function. Currently, setInterval stops counting when the browser is active, but resumes counting when the browser is idle. Is there a way to make setInterv ...

The addition and deletion of classes can sometimes lead to disruptions in the DOM

I've been struggling to phrase this question for a while now. I'm working on a single-page e-commerce site that operates by modifying the HTML in divs and using CSS along with JQuery to show and hide those divs. My problem arises when, occasional ...

Is there a restriction on the number of strings allowed in minimist?

Here is the output received from the code provided below. Question input and i are both true as intended, but why aren't project and p? They are defined in exactly the same way as input and i. $ bin/test --input -p { _: [], update: fa ...

Exploring Laravel 4: Navigating Tables with Relational Models

Edit: error fixed I am managing two interconnected Models: Project and Task. Their relationship is defined as follows: Project.php class Project extends Eloquent { public function tasks() { return $this->hasMany('Task'); ...

Implement a feature in Vuejs where the user can easily move to the next field by simply

I need help implementing a feature that moves the focus to the next field when the enter key is pressed. I've tried the following code, but it's not working as expected. When I added a debugger in the focusNext method inputs[index + 1].focus();, ...

Bringing out the version information in a React/webpack application: A guide

Looking for a way to display the version of every build in your app? I attempted to follow a tutorial to achieve this, but unfortunately, it didn't work for me. The tutorial I used can be found here: Do you know of any other methods that could help a ...