AKPackAttack AKPackAttack - 2 months ago 5x
CSS Question

Button click will not call javascript file

I have been trying to follow the example here to add a dynamic field that is created upon a button click example and have been unable to get it to work.

Here is my javascript file, which I am storing in my static file directory(other static files load fine, filename is 'recipeadd.js'):


var next = 1;
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = '<input autocomplete="off" class="form-control" id="field' + next + '" name="field' + next + '" type="text">';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn- danger remove-me" >-</button></div><div id="field">';
var removeButton = $(removeBtn);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));

var fieldNum = this.id.charAt(this.id.length-1);
var fieldID = "#field" + fieldNum;

Here is what's in my html header, loading both the js and associated css file:

<!--CSS code for recipeadd-->
<link href="{% static 'recipes/css/recipeadd.css' %}" rel="stylesheet">
<!--JS code for reccipeadd-->
<script src="{% static 'recipes/js/recipeadd.js' %}"></script>

Finally, here is the container that contains button 'b1', which I'm trying to have execute the javascript:

<div class="container">
<div class="form-group">
<!--div class="col-xs-4"-->
<label for="recipeName">Recipe Name</label>
<input type="text" class="form-control" id="recipeName">
<div class="form-group">
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Ingredients</label>
<div class="controls" id="profs">
<form class="input-append">
<div id="field"><input autocomplete="off" class="form-control" id="field1" name="prof1" type="text" placeholder="Enter one ingredient per line" data-items="8"/><button id="b1" class="btn add-more" type="button">+</button></div>
<div class="form-group">
<label for="directions">Directions</label>
<textarea class="form-control" rows="5" id="directions"></textarea>

I am teaching myself web development and using the Django framework for this project. Sincerely appreciate any help on this.


First I am assuming you have jQuery on the page, your code is not showing a jQuery reference.

Now assuming that the code adds the elements, I see one issue with adding your click event. You give the remove button the id with a number: id="remove' + (next - 1) + '"

Now when you attach the event, you do not use a number: $("#remove").click(

So either you need to use a number OR better yet, you already have the button element referenced, use that.

removeButton.click( function(){ });