DOM Input Field Tutorial - Get, Set, Remove & Copy Values
What is Input Field Manipulation?
- It means working with input fields to:
- Get value
- Set value
- Remove value
- Copy value
Why is it Important?
- Used in almost every project (forms, UI, validation)
- Helps in:
- Taking user input
- Updating UI dynamically
- Working with arrays, objects later
Accessing Input Field
Use DOM methods:
document.getElementById("idName")
document→ whole HTML pagegetElementById()→ selects element
1. Get Input Value
function getInputFieldValue() {
let inputValue = document.getElementById('name').value;
console.log(inputValue);
}
.valueis used to get input field value
Display Value on Screen
document.getElementById('heading').innerText = inputValue;
innerTextis used for text elements (like h1)
2. Set Input Value
function setInputFieldValue() {
let value = "code step by step";
document.getElementById('name').value = value;
}
- Sets default or custom value in input field
3. Remove / Clear Value
function removeInputFieldValue() {
document.getElementById('name').value = "";
}
- Empty string clears input
4. Copy Value (One Input to Another)
function copyInputFieldValue() {
let whoValue = document.getElementById('who').value;
document.getElementById('name').value = whoValue;
}
- Gets value from one input
- 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
- Use
.valuefor input fields - Use
innerTextorinnerHTMLfor text elements - Always use correct
idto access element - 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
- If ID is incorrect → code will not work