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 >
<img src="img/congrat.png" alt="">
<h3 id="text">hi iam here</h3>
</div>
<div >
<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]
CodePudding user response:
- Please use camelCase for variable names, it's standard.
- This is vulnerable to a HTML injection. Use
innerText
for user-inputted values. Input
is an instance ofHTMLInputElement
. 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 >
<img src="img/congrat.png" alt="">
<h3 id="text">hi iam here</h3>
</div>
<div >
<button onclick="replaceText()">Click Me!</button>
<label for="fname">First name:</label><br>
<input dir="rtl" type="text" id="name">
</div>
</body>
CodePudding user response:
use . value for fetching
const Text = document.getElementById('text');
const Input = document.getElementById('name');
function ReplaceText(){
if( Input.textContent.value == 0){
console.log(1)
}else{
Text.innerHTML = Input.value
}
}
CodePudding user response:
the Input will return the object element and this object have some properties like value to get value of this object.
const Text = document.getElementById('text');
const Input = document.getElementById('name');
function ReplaceText(){
if( Input.textContent.value == 0){
console.log(1)
}else{
Text.innerHTML = Input.value
}
}