Skip to content

Jquery click event not returning anything

My jquery is not alerting anything when I click the button with the id decrease. This is my code. I am using external js file.

$(document).ready(
    $('#decrease').click(function() {
        var beforeIncrement = $('#amt').val();
        alert(beforeIncrement);
    }))

I tried doing this and it is working fine.

$(document).ready(function(){
    alert("Ready");
})

This is the html code:

<div class="row justify-content-center d-flex">
     <button id="decrease" class="btn btn-warning">-</button>
         <input type="number" id="amt" value="1"/>
     <button id="increase" class="btn btn-warning">+</button>
</div>

what’s wrong with my first code snippet?

Answer

The value you pass to ready() needs to be a function.

In your first example, you are passing the return value of $('#decrease').click(...).

This means that $('#decrease').click(...) has to be evaluated immediately, so it is looking for #decrease before the DOM is ready and the element doesn’t exist yet.

ready() then ignores the value you pass to it because it isn’t a function.


Wrap the call to $('#decrease').click(...) in a function, just as you did for alert(...) in the second example.


You also have a missing ); at the end but I’m guessing that just got cut off when you transcribed your code to the question.