Mr.Ulis
Mr.Ulis

Reputation: 157

How to make input field null after button is clicked?

I want the input field to be empty after I press the search button so that I can see the placeholder text. How can I make this happen?

        let inp1 = document.querySelector('#inp1');

        let arrai = ["cake", "apple", "banan"];



          function engine(){
            for(let srch of arrai){
              if (inp1.value === srch) {
                window.location.href = inp1.value+".html"
              } else {
                inp1.focus();
                inp1.style.border = "2px solid red";
                inp1.placeholder = "failed";
              }
            }
          }

Upvotes: 0

Views: 1420

Answers (2)

epascarello
epascarello

Reputation: 207511

The answer to your issue is you would need to set the value to be empty to see the placeholder. But your code is only going to work for the first value in your array since you assume if the match is not valid it is wrong. That is not the case since you have not checked all the possibilities.

What you would need to do is alter your check. It would be better to use includes instead of a for loop.

function engine(){
  var value = inp1.value.toLowerCase()
  var hasMatch = arrai.includes(value)
  if (hasMatch) {
    window.location.href = value + ".html"        
   } else {
     inp1.value = ''; // what you originally asked for
     inp1.focus();
     inp1.style.border = "2px solid red";
     inp1.placeholder = "failed";
   }
 }

to do it with a for loop

function engine(){
  var hasMatch = false
  for(let srch of arrai){
    if (inp1.value === srch) {
      window.location.href = inp1.value + ".html"
      hasMatch = true
    }
  }
  if (!hasMatch) {
    inp1.value = '';
    inp1.focus();
    inp1.style.border = "2px solid red";
    inp1.placeholder = "failed";
  }
}

Upvotes: 1

Souritra Das Gupta
Souritra Das Gupta

Reputation: 130

inp1.value ='';

This will set the input to blank and placeholder should display. If that doesn't work try

inp1.innerHTML = '';

Generally innreHTML only applies to divs,spans, etc. Inputs have a value.

Upvotes: 2

Related Questions