Home > Mobile >  How to listen to a form field in JavaScript
How to listen to a form field in JavaScript

Time:01-30

I would like to be able to listen to a field in an input but without validating or clicking on anything

and if this field is empty then display an image

if the field is filled then no image is displayed

for that I will use el surval of the mouse above a div

here is my code but it seems to be a problem with the city condition in order to know if it is empty or not

I give you my code

I have been looking for several hours

<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onm ousemove Event</h2>
<input  type="text" name="ville" value="" id="ville" placeholder="" required="required" />
<div style ="width: 200px;
height: 100px;
border: 1px solid black;"onmousemove="myFunction(event)" onm ouseout="clearCoor()"></div>
<img id="myImgaa" src="" width="107" height="98">
<script>
function myFunction() {
  //alert(document.getElementsByName("ville"));
if (document.getElementsByName('ville') !== null && document.getElementsByName('ville') !== '')
{ document.getElementById("myImgaa").src = "https://www.w3schools.com/jsref/img_pulpit.jpg";}
  
  else

{ document.getElementById("myImgaa").src = "";}
  
}
function clearCoor() {
  

}
</script>
</body>
</html>

CodePudding user response:

You are getting a NodeList with getElementsByName. But you actually want a single element like getElementById.

You can use the following selector like: querySelector('[name="ville"]').
And you want actually want to check against it's value attribute. so your if statement should be as follow:

function myFunction() {
  const ville = document.querySelector('[name="ville"]');
  if (ville !== null && ville.value !== '')
  { 
    document.getElementById("myImgaa").src = "https://www.w3schools.com/jsref/img_pulpit.jpg";
  } else { 
    document.getElementById("myImgaa").src = "";
  }
}

  
  • Related