Home > Enterprise >  how to get the value from the first text box and assign that value to the second text box on click o
how to get the value from the first text box and assign that value to the second text box on click o

Time:10-16

I am trying to code where if I enter any value in my Text-1 box so I want that value to be displayed in my Text-2 box. If someone can please help me how to do it. Below is my HTML & `

function displayText(){
    var txt1 = document.getElementById('txt-1');
    var btn1 = document.getElementById('btn1');
    var out1 = document.getElementById('output1');
    out1.innerHTML = txt1.value; 
    btn1.addEventListener('click',displayText);
}
displayText();
<label for="text-box">Username:</label>
        <input type="text" id="txt-1" placeholder="Text Box-1">
        <input type="text" id="output1" placeholder="Text Box-2">
        <input type="button" id="btn1" value="Click Me">
        

JS` code

CodePudding user response:

Assign the value of the first input to the value of the second input.

out1.value = txt1.value;

Since you only really need the function to be called when the button is clicked you can move all of the lines of code with the exception of that line outside of function. That way you don't need to call displayText when the page loads.

Note: you might also consider changing <input type="button"> to an actual button: <button type="button">Click me</button>.

Note 2: Your for attribute on the label should point to the id of the first input, not "text-box".

const txt1 = document.getElementById('txt-1');
const btn1 = document.getElementById('btn1');
const out1 = document.getElementById('output1');

btn1.addEventListener('click', displayText);

function displayText() {
  out1.value = txt1.value;
}
<label for="txt-1">Username:</label>
<input type="text" id="txt-1" placeholder="Text Box-1">
<input type="text" id="output1" placeholder="Text Box-2">
<button type="button" id="btn1">Click Me</button>

CodePudding user response:

Based on the code out1.value should be used as want to assign that to another text-box. But if wants to display within p tag, div tag then innerHTML should be used.

function displayText(){
    var txt1 = document.getElementById('txt-1');
    var btn1 = document.getElementById('btn1');
    var out1 = document.getElementById('output1');
    out1.value = txt1.value; 
    
}
btn1.addEventListener('click',displayText);
<label for="text-box">Username:</label>
        <input type="text" id="txt-1" placeholder="Text Box-1">
        <input type="text" id="output1" placeholder="Text Box-2">
        <input type="button" id="btn1" value="Click Me">
        

  • Related