2

I have an input tag I can change its attributes which takes some value e.g.

<input type="text">

<script>
    var inputEls = document.querySelector("input");
    inputEls.placeholder = "Enter Name";
</script>

But how I can change put attributes that doesn't take attributes say autofocus.

inputEls.autofocus ?? 
abhimanyuaryan
  • 3,882
  • 5
  • 41
  • 83

1 Answers1

3

The autofocus property is a boolean property, so you set it to true or false:

inputEls.autofocus = true;

Not all properties like that are boolean. For example, the autocomplete property has a string value, either "off" or "on".

You can look up things like this at the Mozilla Developer Network Wiki or in the sprawling HTML5 spec. (edit — I went to look for a good link into the W3C spec, but I can't find autofocus documented there.)

Note that setting the autofocus flag doesn't seem to do anything in Firefox at least. I've tried

<!DOCTYPE html>
<html>
  <body>
    <input id=x>
    <script>
      document.getElementById("x").autofocus=true;
    </script>
  </body>
</html>

in a small test file and it doesn't do anything in Firefox, but it works in Chrome. Similarly, that same test with the "autofocus" attribute in the HTML and the JavaScript setting it to false doesn't turn it off either.

In either Chrome or Firefox, setting the flag after the page has fully loaded doesn't seem to have any effect.

Pointy
  • 405,095
  • 59
  • 585
  • 614