Umair Jameel Umair Jameel - 4 months ago 9
HTML Question

Fire events on more than one element in html

I have a jquery code

$(function() {
$("input").on("mouseover", function() {
var a = $('input').attr('name');
populate(a);
});
});


I have three input elements.

Computer Language: <br>
<div>
<datalist id="language"></datalist>
<input type="text" list="language" name= "language" id="search"/>
</div>
<br>
Country: <br>
<div>
<datalist id="country"></datalist>
<input type="text" list="country" name= "country" id="search" />
</div>
<br>

Degree: <br>
<div>
<datalist id="degree"></datalist>
<input type="text" list="degree" name= "degree" id="search"/>
</div>


Now,
mouseover
event only fires that have name
language
(or the top input element). Why
mouseover
event is not being fired for 2nd and 3rd input elements?

Answer

Note: The ids are not meant to be duplicated. You have used id="search" many times.

You need to use the context-sensitive this keyword:

$(function() {
  $("input").on("mouseover", function() {
    var a = $(this).attr('name');
    populate(a);
  });
});

To answer your question:

The reason being, you are executing the .attr() (which is one of many functions that processes only one element) on the first matched element.

Comments