Home > Back-end >  The value of the placeholder in HTML form input cannot be changed with JavaScript from inside of a f
The value of the placeholder in HTML form input cannot be changed with JavaScript from inside of a f

Time:05-11

Problem & Research: I have to automatically change the value of the placeholder of an HTML form input inside a JavaScript function. I did some research. The given code does not work for my case. I found a way around it, but I think there must be a better solution. Also, I wonder why the code example given in w3school doesn't work for my case.

Requirement: Only HTML and Vanilla JavaScript

The Code:

<body>
    <h1>Test JS</h1>
    <form id="search">
        <div id="input_id">
            <input type="text" id="id" name="name" required placeholder="Search...">    
        </div>
        
        <button type="submit">Submit</button>
    </form>

    <script>
        document.getElementById("id").placeholder = "This works outside of the function" 
        document.getElementById('search').addEventListener('submit', SearchIt)
        async function SearchIt (event) {
            event.preventDefault()
            var newVal = "123"
            document.getElementById("id").placeholder = newVal //This line does not work inside the function, why?
            //The following line works but I am looking for a better solution (Vanilla JS only).  
            document.getElementById("input_id").innerHTML = "<input type='text' id='id' name='name' required placeholder="   newVal   ">"
        }
    </script>

</body>

CodePudding user response:

Due to the required attribute, the browser is preventing the form from being submitted when the input is empty. But if you type something into the form to satisfy the validity, the placeholder will no longer be seen because there's text in the input.

Either remove the required attribute, or set the input value to the empty string while setting the new placeholder in order to see the new placeholder.

document.getElementById("id").placeholder = "This works outside of the function"
document.getElementById('search').addEventListener('submit', SearchIt)
async function SearchIt(event) {
  event.preventDefault()
  document.getElementById("id").placeholder = '123';
}
<h1>Test JS</h1>
<form id="search">
  <div id="input_id">
    <input type="text" id="id" name="name" placeholder="Search...">
  </div>

  <button type="submit">Submit</button>
</form>

document.getElementById("id").placeholder = "This works outside of the function"
document.getElementById('search').addEventListener('submit', SearchIt)
async function SearchIt(event) {
  event.preventDefault()
  document.getElementById("id").placeholder = '123';
  document.getElementById("id").value = '';
}
<h1>Test JS</h1>
<form id="search">
  <div id="input_id">
    <input type="text" id="id" name="name" required placeholder="Search...">
  </div>

  <button type="submit">Submit</button>
</form>

  • Related