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?

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

the second call should be on('blur')
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']").

Comments

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
})

2 Comments

I have to manage [calcdensity='yes'] and [densitybtn='yes']. How can we add [calcdensity='yes']?
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.