Rupesh Bhandari
Rupesh Bhandari

Reputation: 86

Clearing textfield value

I'm trying to clear the textfield in html using javscript if the given condition is met. For ex:- if the user types awesome in textfield then it should reset the textfield (no blank space nothing).

<html>
<input type="text" id="real" onkeypress="blank()" placeholder="tempo"/><br>
<script>
function blank(){
        if(document.getElementById('real').value=="awesome"){
            real.value='';
        }
}
</script>
</html>

Upvotes: 1

Views: 69

Answers (5)

Harit
Harit

Reputation: 21

You where facing issue with input event "onkeypress" if change the event and use "onkeyup" issue will be resolved.

 <html>
<script>
function blank() {
   var real = document.getElementById('real');
   if (real.value == "awesome") {
      real.value = '';
   }
}
</script>
<input type="text" id="real" onkeyup="blank()" placeholder="tempo"/><br>
</html>

Upvotes: 0

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11707

Use variable real to store input element and use onkeyup event:

function blank() {
   var real = document.getElementById('real');
   if (real.value == "awesome") {
      real.value = '';
   }
}
<input type="text" id="real" onkeyup="blank()" placeholder="tempo" />
<br>

Another good example would be:

document.addEventListener('DOMContentLoaded', function() {
  var real = document.getElementById('real');
  real.addEventListener('keyup', blank, false);
}, false)

function blank() {
  if (this.value === "awesome") {
    this.value = '';
  }
}
<input type="text" id="real" placeholder="tempo" />
<br>

Upvotes: 1

kanudo
kanudo

Reputation: 2219

<html>
<input type="text" id="real" onkeypress="blank()" placeholder="tempo"/><br>
<script>
function blank(){
    var real = document.getElementById('real');
    if(real.value=="awesome"){
        real.value='';
    }
}
</script>
</html>

Upvotes: 0

Source Matters
Source Matters

Reputation: 1221

Change the line

real.value=''

to

document.getElementById('real').value = '';

You can't just say "real.value" because javascript doesn't know what "real" is.

Upvotes: 0

Radosław Miernik
Radosław Miernik

Reputation: 4094

Here real is undefined, so instead of

...
real.value = '';
...

do this

...
document.getElementById('real').value = '';
...

Upvotes: 2

Related Questions