Prince Prince - 4 months ago 10
jQuery Question

Display an alert in javascript

I am new to javascript and I was following a tutorial where based on the code below, the button content was supposed to change to

adding
before displaying the alert but my code is not working



<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<form class="form-item">
<div class="cart">
<input type="submit" value="Add to Cart" />
</div>
</form>


<script>
$(document).ready(function(){
$("button").click(function(){
button_content.html('Adding...'); //Loading button text
alert("Item added to Cart!"); //alert user
});
});
</script>





How can I solve this problem ?

Answer

Give this code a try for a few reasons.

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<form class="form-item">
    <div class="cart">
        <!--<input type="submit" value="Add to Cart" />-->

        <!-- First use a button not an input and give it an ID -->
        <button id="btn_add" type="submit">Add to Cart</button>
    </div>
</form>
<script>

    // You can shorten up the ready statement
    //$(document).ready(function(){

    $(function(){

        // Now bind a click handler with button's ID

        // This is an older way of binding in jQuery
        // $("#btn_add").click(function(){

        // Use jQuery's on() instead.
        $("#btn_add").on("click", function(){

            // Change the HTML of the button by getting it by it's new ID
            // button_content.html('Adding...'); //Loading button text

            $("#btn_add").html('Adding...');

            alert("Item added to Cart!"); //alert user
        });
    });
</script>

Use an ID anywhere that you can. Feel free to shorten up your ready statement. Use jQuery's on handler instead of click.