I need to display input text over image by JavaScript. mean any user input text will appears in image. but all i get it [object HTMLInputElement]
html
<body>
<div class="congrat">
<img src="img/congrat.png" alt="">
<h3 id="text">hi iam here</h3>
</div>
<div class="name">
<button onclick="ReplaceText()">Click Me!</button>
<label for="fname">First name:</label><br>
<input dir="rtl" type="text" id="name">
</div>
<script src="app.js"></script>
</body>
JavaScript code
const Text = document.getElementById('text');
const Input = document.getElementById('name');
function ReplaceText(){
if( Input.textContent.value == 0){
console.log(1)
}else{
Text.innerHTML = Input
}
}
when clicked in button its shown me ..[object HTMLInputElement]
innerText for user-inputted values.Input is an instance of HTMLInputElement. It has a .textContent property, but stringified (as you did) it becomes the [object X] placeholder. Use .value instead.const text = document.getElementById('text');
const input = document.getElementById('name');
function replaceText(){
if (!input.value) {
console.log(1)
} else {
text.innerText = input.value;
}
}
<body>
<div class="congrat">
<img src="img/congrat.png" alt="">
<h3 id="text">hi iam here</h3>
</div>
<div class="name">
<button onclick="replaceText()">Click Me!</button>
<label for="fname">First name:</label><br>
<input dir="rtl" type="text" id="name">
</div>
</body>
the Input will return the object element and this object have some properties like value to get value of this object.
edit by @0xLogN:
avoid use innerHTML with input to avoid js injection, use innerText
const Text = document.getElementById('text');
const Input = document.getElementById('name');
function ReplaceText(){
if( Input.textContent.value == 0){
console.log(1)
}else{
Text.innerText = Input.value
}
}