Reputation: 167
I have the following HTML/JS code:
<!DOCTYPE html>
<html>
<body>
<input type='text' id='action' placeholder='defualt'>
<button type='button' onclick='document.getElementById("action").placeholder="it worked!"'>Change Placeholder</button>
</body>
</html>
When the button is pressed, the placeholder
value of the action
text
input
field is set to 'it worked!'
What I would like to do is make the script set the placeholder
of the field whatever the user puts into it when the user presses the button. How should I do this?
Upvotes: 1
Views: 561
Reputation: 14531
To access the input element's value, you can access .value
property. Then just like you set the placeholder, you can assign that to .placeholder
property.
Finally, if you wish to have the placeholder visible immediately, you can reset the value by setting it to an empty string.
function setPlaceHolder() {
var input= document.getElementById("action");
input.placeholder=input.value;
input.value = "";
}
<!DOCTYPE html>
<html>
<body>
<input type='text' id='action' placeholder='defualt'>
<button type='button' onclick='setPlaceHolder();'>Change Placeholder</button>
</body>
</html>
Upvotes: 2
Reputation: 7591
Try this
function myfns() {
var x = document.getElementById("action").value;
console.log(x)
document.getElementById("action").placeholder = x
document.getElementById("action").value = "";
}
<html>
<body>
<input type='text' id='action' placeholder='defualt'>
<button type='button' onclick='myfns()'>Change Placeholder</button>
</body>
</html>
Upvotes: 2