1

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?

1
  • Have you attempted this first? Based on your code (using document.getElementById) it appears you would know how to do that. Commented Nov 26, 2017 at 4:35

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.