0

In the following html, javascript, bootstrap form the click event handler works properly and adds a new dynamic row but the remove button does not alert out anything when clicked on it. There are no error messages on the debugger console so i am not sure what's wrong.

<!DOCTYPE html>
<html lang="en-us"> 
<head>
    <meta charset="utf-8">
    <title> Reggie Scenarios </title>
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <!-- #CSS Links -->
    <!-- Basic Styles -->
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

    <!-- Credits: http://bootsnipp.com/snippets/featured/responsive-navigation-menu 

    -->
    <link rel="stylesheet" type="text/css" href="leftMenu.css">

    <script src="scenario.js"></script>
</head>

<body>


      <div class="mainForm">
        <div class="container">
          <h2>Scenario</h2>
          <form id="bookForm" method="post" class="form-horizontal">
                <div class="form-group">
                    <label class="col-xs-1 control-label">Book</label>
                    <div class="col-xs-4">
                        <input type="text" class="form-control" name="book[0].title" placeholder="Title" />
                    </div>
                    <div class="col-xs-4">
                        <input type="text" class="form-control" name="book[0].isbn" placeholder="ISBN" />
                    </div>
                    <div class="col-xs-2">
                        <input type="text" class="form-control" name="book[0].price" placeholder="Price" />
                    </div>
                    <div class="col-xs-1">
                        <button id= "plusButton1" type="button" class="btn btn-default addButton"><span class="glyphicon glyphicon-plus"></span></button>
                    </div>
                </div>

                <div class="form-group hide" id="bookTemplate">
                    <div class="col-xs-4 col-xs-offset-1">
                        <input type="text" class="form-control" name="title" placeholder="Title" />
                    </div>
                    <div class="col-xs-4">
                        <input type="text" class="form-control" name="isbn" placeholder="ISBN" />
                    </div>
                    <div class="col-xs-2">
                        <input type="text" class="form-control" name="price" placeholder="Price" />
                    </div>
                    <div class="col-xs-1">
                        <button id = "removeButton" type="button" class="btn btn-default removeButton"><span class="glyphicon glyphicon-minus"></span></button>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-5 col-xs-offset-1">
                        <button type="submit" class="btn btn-default">Submit</button>
                    </div>
                </div>
            </form>

        </div>
      </div>

</body>

<script>
bookIndex = 0;
$(document).ready(function() {

    $(".removeButton").click(function() {
        alert("Remove button was clicked!");
        var id = $(this).attr("id");
        alert(id);
        var $row  = $(this).parents('.form-group'),
            index = $row.attr('data-book-index');
        // Remove element containing the fields
        $row.remove();

    });

    $(".addButton" ).click(function(event) {
        alert("Add button was clicked!");
        bookIndex++;
        var $template = $('#bookTemplate'),
            $clone    = $template
                            .clone()
                            .removeClass('hide')
                            .removeAttr('id')
                            .attr('data-book-index', bookIndex)
                            .insertBefore($template);

        $clone
            .find('[name="title"]').attr('name', 'book[' + bookIndex + '].title').end()
            .find('[name="isbn"]').attr('name', 'book[' + bookIndex + '].isbn').end()
            .find('[name="price"]').attr('name', 'book[' + bookIndex + '].price').end();


    });


});

Please advise on what i may be doing wrong. I have created a jsfiddle here: https://jsfiddle.net/snehilw/7Luxo0L4/

In the fiddle, the add button works, but the remove button won't work. I do not get any errors in the debugger console.

Please advise,

thanks!

1
  • check this fiddle Commented Jun 2, 2015 at 5:33

3 Answers 3

3

Use event delegation. This will bind event to the elements inside #bookForm having removeButton class and even added dynamically.

$('#bookForm').on('click', '.removeButton', function() {
    // Event handler
});

https://learn.jquery.com/events/event-delegation/

Demo: https://jsfiddle.net/tusharj/7Luxo0L4/2/

Sign up to request clarification or add additional context in comments.

2 Comments

Yup. @Rookie, you need to do this because your .removeButton does not exist when you add the click handler. The method suggested by @Tushar actually adds an event to the parent that will run on any .removeButton underneath it, regardless of when it's added to the dom.
Thanks Tushar and ntdb for the explanation, thats very insightful & this is working for me now. I read up the documentaion on event delegation, thanks a ton for guiding me on this!
2

Use delegate.

Replcae remove button click code with this

 $(document).delegate('.removeButton','click',function(){
  //your code
});

Jsfiddle

1 Comment

delegate calls on, so it is better to call on directly github.com/jquery/jquery/blob/master/src/event/alias.js#L31 There might be chances that delegate will be deprecated in near future.
0

You tried jQuery('#addRow').trigger("click");

You first have to have a click function. What I would do is this - since the function is provided (you can modify the link to take out the inline JavaScript, right?):

$('#addRow').click(function() {

  addNewRow();

})

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.