0

I have this function onclick event of custom tag densitybtn='yes'

$("[densitybtn='yes']").on('click', function () {
    var no_of_people = 0;
    //calcdensity
    $("[calcdensity='yes']").each(function () {
        no_of_people = parseInt($(this).val()) + no_of_people;
    });
    var total_density = parseInt(carpetArea) / parseInt(no_of_people);
    $("#densityVal").html(Myval);
});

Can i extend same code by extending it to $("[calcdensity='yes']").on('blur')

$("[calcdensity='yes']").on('blur').$("[densitybtn='yes']").on('click', function () {

});

Am not sure on executing same code on different events

Let me know is this method correct? or is there any alternative way available?

Tushar
  • 85,780
  • 21
  • 159
  • 179
Mangesh Sathe
  • 1,987
  • 4
  • 21
  • 40

3 Answers3

6

Define the function normally (not as an anonymous function) and pass the function to the event listeners

function listener() {
   var no_of_people = 0;
   //calcdensity
   $("[calcdensity='yes']").each( function() {
      no_of_people = parseInt($(this).val())+no_of_people;
   });
   var total_density = parseInt(carpetArea)/parseInt(no_of_people);
   $("#densityVal").html(Myval);
}

$("[densitybtn='yes']").on('click', listener);
$("[calcdensity='yes']").on('blur', listener);
Tushar
  • 85,780
  • 21
  • 159
  • 179
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
0

Nope, thats not a good practise. Instead you can write a function for the second intent and call it on blur of $("[calcdensity='yes']").

dotnetom
  • 24,551
  • 9
  • 51
  • 54
0

You can bind multiple events using jQuery's .on() method by space-separating the event arguments.

$("[densitybtn='yes']").on('click blur', function() {
    // actions to perform
})


You can bind events to multiple elements using jQuery's .add() method.

$("[densitybtn='yes']").add("[calcdensity='yes']").on('click blur', function() {
    // actions to perform
})
Antonio Dangond
  • 149
  • 1
  • 8
  • I have to manage [calcdensity='yes'] and [densitybtn='yes']. How can we add [calcdensity='yes']? – Mangesh Sathe May 12 '15 at 06:26
  • Sorry, I misread the question. Do you want to run the function on both 'click' and 'blur' for both [calcdensity='yes'] and [densitybtn='yes'], or just 'click' for the first and 'blur' for the second? – Antonio Dangond May 12 '15 at 06:36