Home Courses DOM Input Field Tutorial - Get, Set, Remove & Copy Values

DOM Input Field Tutorial - Get, Set, Remove & Copy Values

What is Input Field Manipulation?

  1. It means working with input fields to:
  2. Get value
  3. Set value
  4. Remove value
  5. Copy value


Why is it Important?

  1. Used in almost every project (forms, UI, validation)
  2. Helps in:
  3. Taking user input
  4. Updating UI dynamically
  5. Working with arrays, objects later


Accessing Input Field

Use DOM methods:


document.getElementById("idName")

  1. document → whole HTML page
  2. getElementById() → selects element


1. Get Input Value


function getInputFieldValue() {
let inputValue = document.getElementById('name').value;
console.log(inputValue);
}

  1. .value is used to get input field value


Display Value on Screen


document.getElementById('heading').innerText = inputValue;

  1. innerText is used for text elements (like h1)


2. Set Input Value


function setInputFieldValue() {
let value = "code step by step";
document.getElementById('name').value = value;
}

  1. Sets default or custom value in input field


3. Remove / Clear Value


function removeInputFieldValue() {
document.getElementById('name').value = "";
}

  1. Empty string clears input


4. Copy Value (One Input to Another)


function copyInputFieldValue() {
let whoValue = document.getElementById('who').value;
document.getElementById('name').value = whoValue;
}

  1. Gets value from one input
  2. Sets it into another


Example HTML Structure


<input type="text" id="name" placeholder="enter name">
<input type="text" id="who" placeholder="enter other name">

<button onclick="getInputFieldValue()">Get Value</button>
<button onclick="setInputFieldValue()">Set Value</button>
<button onclick="removeInputFieldValue()">Remove Value</button>
<button onclick="copyInputFieldValue()">Copy Value</button>


Key Points to Remember

  1. Use .value for input fields
  2. Use innerText or innerHTML for text elements
  3. Always use correct id to access element
  4. Functions are triggered using button click


Common Mistakes

Mistake 1: Forgetting .value


document.getElementById('name') // gives element, not value

Correct:


document.getElementById('name').value


Mistake 2: Using innerText on input


input.innerText // wrong

Correct:


input.value

Mistake 3: Wrong ID

  1. If ID is incorrect → code will not work


Share this lesson: