skip to Main Content

i need to run the function changePageTitle() if the textbox with the ID "title" is empty and if not then run newPageTitle = "please choose title" document.title = newPageTitle;
here is my code (I am trying to make something that changes the title of the page to what ever I put in the text box)

<html>

<head>
  <title>
    please choose title
  </title>
</head>

<body>
    <input type="text" id="title" size="150" oninput="changePageTitle()">
  <br>
  <button onclick="changePageTitle()">
    *click me if page title doesn't change
  </button>

  <script type="text/javascript">
    function changePageTitle() {
      newPageTitle = document.getElementById('title').value;
      document.title = newPageTitle;
    }
const interval = setInterval(function(){
  //here is where I want to put the check
}, 1000);
  </script>
</body>

</html>

2

Answers


  1. const interval = setInterval(function(){
      if(document.getElementById("title").value == ''){
         newPageTitle = "please choose title";
         document.title = newPageTitle;
      }
    }, 1000);
    
    
    document.getElementById("title").value == ''
    

    Will return true if the input is empty.

    Is that what you’re after?

    Login or Signup to reply.
  2. Simply check the variable directly; you already have an event handler which will be fired on input so setInterval is unnecessary.

    function changePageTitle() {
      let newPageTitle = document.getElementById('title').value;
      if (newPageTitle === '') {
        newPageTitle = "please choose title";
      }
      document.title = newPageTitle;
    }
    

    Try it:

    function changePageTitle() {
      let newPageTitle = document.getElementById('title').value;
      if (!newPageTitle) {
        newPageTitle = "please choose title";
      }
      document.title = newPageTitle;
    }
    <html>
    
    <head>
      <title>
        please choose title
      </title>
    </head>
    
    <body>
      <input type="text" id="title" size="150" oninput="changePageTitle()">
      <br>
      <button onclick="changePageTitle()">
        *click me if page title doesn't change
      </button>
    </body>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search