Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML multiple events to trigger the same function

Is there a way to have multiple events (e.g. oninput, onblur) trigger exactly the same function in the HTML?

This is the HTML that I'm trying to simplify:

<input id="Email" name="Email" type="text" oninput="toggleSuccessIcon(this, isEmail)" onblur="toggleSuccessIcon(this, isEmail)">

I know this is possible in jQuery as explained here, but since I have a lot of different inputs (e.g. address, postcode, etc.) that need to call different functions (e.g. toggleSuccessIcon(this, isAddresss), toggleSuccessIcon(this, isPostCode), etc.) I wanted to avoid having a long and messy initialisation in the JavaScript. However, if I am being foolish by doing this in HTML rather than JQuery I'd appreciate an explanation as to the advantage of using JQuery.

Note that isEmail, isAddress, isPostCode, etc. is a function name.

like image 367
Tarostar Avatar asked Apr 22 '15 06:04

Tarostar


People also ask

How do I pass multiple events in Javascript?

JQuery's bind allows multiple events, like so: $(window). bind('mousemove touchmove', function(e) { //do something; });

Can multiple event handlers be added to a single element?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.


1 Answers

You can use data as:

<input class="configurable-events" type="text" data-events="blur focus click" data-function="myFunction" />
<input class="configurable-events" type="password" data-events="blur focus" data-function="myPasswordFunction" />

in jQuery you can use something like:

$('.configurable-events').each(function(){
    $(this).on($(this).data('events'), function(){
      $(this).data('function')($(this));
    });
});

function myFunction(myInput) {
  console.log(myInput.value());
}

function myPasswordFunction(myPasswordInput) {
  console.log(myPasswordInput.size());
}
like image 96
Mihai Matei Avatar answered Oct 31 '22 10:10

Mihai Matei