0

Consider the following code.

$(function(){

    $(".notes").click(function(){
        console.log('hi');          
    })
})

    <a data-shipmentid="1" href="#" class="notes btn btn-primary btn-xs">Notes</a>
    <a data-shipmentid="1" href="#" class="notes btn btn-primary btn-xs">Notes</a>
    <a data-shipmentid="1" href="#" class="notes btn btn-primary btn-xs">Notes</a>
    <a data-shipmentid="1" href="#" class="notes btn btn-primary btn-xs">Notes</a>
    <a data-shipmentid="1" href="#" class="notes btn btn-primary btn-xs">Notes</a>

The purpose is to log a message when any of the hyperlink is clicked. The issue I am facing is that if I click on a hyperlink, then the console it getting the message "hi" 5 times ( the total number of hyperlinks with the class "notes" )

I understand that something is wrong. How do I check what is wrong here in this case? I see console is not displaying any error messages. Anyone has any idea why the event is firing up multiple times?

8
  • that should only be done once - can you reproduce in a fiddle or snippet? Commented Jan 16, 2015 at 1:22
  • Yes, you are right, it should only execute once. And I can't reproduce it on JsFiddle( I tried that ) with the same code that I am using on my project ( which is a large project ). I need some suggestions on where to look for possible errors Commented Jan 16, 2015 at 1:24
  • I also tried to upgrade jQuery from 1.10 to 1.11 thinking that it may be the issue with jquery core, but it isn't Commented Jan 16, 2015 at 1:24
  • 1
    See what gets selected with console.log($(".notes")) Commented Jan 16, 2015 at 1:25
  • 1
    You can always try $(".notes").off().click... Commented Jan 16, 2015 at 1:41

2 Answers 2

1

The answer provided by Shanimal worked!

$(function(){
 $(".notes").off().click(function(){
    console.log('hi');          
   })
})
Sign up to request clarification or add additional context in comments.

Comments

0

How about use .one()

$(function(){

    $(".notes").one('click', function(){
        console.log('hi');          
    })
})

Comments

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.