Clicking the button will not trigger the execution of the JavaScript file

I have been struggling to implement a dynamic field that is supposed to be generated upon clicking a button. Unfortunately, the example I've been following from here has not been working for me.

Below is the content of my JavaScript file 'recipeadd.js' located in my static file directory:

$(document).ready(function(){

var next = 1;
$("#b1").click(function(e){
    alert("Hi");
    e.preventDefault();
    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);
    $(addto).after(newInput);
    $(addRemove).after(removeButton);
    $("#field" + next).attr('data-source',$(addto).attr('data-source'));
    $("#count").val(next);

        $("#remove").click(function(e){
            e.preventDefault();
            var fieldNum = this.id.charAt(this.id.length-1);
            var fieldID = "#field" + fieldNum;
            $(this).remove();
            $(fieldID).remove();
        });
    });
    });

The code below is added to my HTML header to load both the associated JS and CSS files:

   <!--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>

Lastly, here's the container which includes the button 'b1' that should trigger the JavaScript functionality:

<div class="container">
<div class="form-group">
    <label for="recipeName">Recipe Name</label>
    <input type="text" class="form-control" id="recipeName">
</div>
<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>
            </form>
        </div>
    </div>
</div>
<div class="form-group">
    <label for="directions">Directions</label>
    <textarea class="form-control" rows="5" id="directions"></textarea>
</div>

I am self-teaching web development and utilizing the Django framework for this project. Any assistance on this matter would be greatly appreciated.

Answer №1

Assuming jQuery is present on the page, it seems your code lacks a reference to jQuery.

If the code is adding elements dynamically, there appears to be an issue with how you are attaching the click event. The remove button is given an id with a number: id="remove' + (next - 1) + '"

However, when you attach the event, you are not using a number: $("#remove").click(

It would be better to either use a number in the click event or, even better, utilize the already referenced button element.

removeButton.click( function(){ });

Answer №2

Learning something new can sometimes involve a few bumps in the road. In my case, I realized that having a reference to jQuery was essential even if I had already included a JavaScript file. Once I downloaded and added the necessary jQuery reference, everything started working perfectly - big thanks for the help!

<!--jQuery core code-->
<script src="{% static 'recipes/js/jquery-3.1.0.min.js' %}"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arranging inline-flex elements within a div container

I have been struggling to position two elements side by side within a single div, where the second element should be on the right side. <div className={classes.container}> <div className={classes.first}> First </div> <d ...

Is there a way to eliminate the gap between two divs that are positioned one on top of the other vertically

Looking at the image, I need the div above the footer to be flush with it. I've tried various solutions and need help from someone with more experience. Here is the HTML and CSS code for reference. Illustration link HTML and CSS .content{ marg ...

The jquery scrolltop() function provides the value of the scroll position prior to the current

Using the jQuery function element.scrollTop(), I attempted to retrieve the current scroll position of the page with the following line of code: var currentScrollPosition = $('html').scrollTop() || $('body').scrollTop(); However, this ...

JavaScript can be used to set the active tab index in Internet Explorer

Dealing with IE is a constant struggle for me. My goal is to implement validation that runs from a button within a tab to prevent users from skipping tabs without filling in data, which could potentially cause issues with my database queries. $("[id ...

js extracting information from the XML response using response.text()

Currently, I am sending an ajax request to an API that returns data in XML format. Upon receiving the responseXml data, it gets displayed, but I'm unsure about how to parse it and access specific data elements such as item.line or item.origTime. Shou ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

Unable to retrieve private field using a public getter method through a proxy

When retrieving data from a VueX Module using a Getter, the Object is enclosed within a Proxy that triggers the following error: TypeError: attempted to get private field on non-instance when attempting to access a private property with a public getter. ...

Concerning geoext

I am currently working on creating a framework for overlaying layers on the web. I am using geoserver to publish the layers and the geoext tree.js example to display all the layers in a tree-like panel. However, I'm encountering an issue with zooming ...

Customizing an external module class using CSS module pattern in React

Is there a way to locally override an external module's CSS class for a specific component? Here is my current code: import `style` from './style.module.css' // local CSS module import `ExternalComponent` from 'ExternalComponent&apos ...

What are some methods to conceal an email address using Javascript?

let user = 'alex'; let domain = 'gmail.com'; let send = 'msg'; document.getElementById("email").href = "ma" + send + "ilto:" + user + "@" + domain; <a id="email"> <img src="imgs/pic.jpg"> </a> I have been w ...

Is there a way to have a dropdown menu automatically expand when a selection is made in a different dropdown menu?

Within this product upload form, I have integrated five cascading drop-down lists using HTML, complemented by embedded Javascript to dynamically fill the options in these lists. My main query pertains to enabling the second drop-down list to appear automat ...

Various hues blending and intertwining with one another

https://i.stack.imgur.com/zLrNK.png Could someone please clarify what is happening here? I'm attempting to change the background color to dodgerblue, but for some reason, the white background color is still showing through. Below is the code snippet ...

Adjust item size and move them into the panel

I am looking to create a panel that arranges items in a specific layout shown here: https://i.stack.imgur.com/qw3lS.png Below is the code I have attempted so far: import React, { useCallback, useEffect } from "react"; import { Box, Grid, Tab, T ...

Guide to displaying the output of a JS calculation in a Bootstrap modal dialog box

I have a HTML and JavaScript code that determines the ideal surfboard for the user based on their input data (style, experience, height, weight) and displays the recommended surfboard type. Here is the initial code snippet I attempted to use: function c ...

Unique Title: "Personalized Styling Category for dijit/layout/ContentPane"

I am looking to add a custom CSS Class to a dijit/layout/ContentPane in order to apply my own styling. This is because I have multiple tabs in a TabContainer where my ContentPanes are located and I want to avoid duplicating borders. Adding a border around ...

I can't seem to figure out why the removeChild() function is not functioning properly in my

Recently, I've been working on a search website where users can input either a partial or full name and then click a button to display a list of actors whose names contain that specific string in a hint-like fashion. These names are sourced from a MyS ...

Generating model objects from JSON using Node.js

While it's common knowledge that any JSON can be easily converted into a JavaScript object, I'm facing a challenge with the GitHub API. I need to retrieve the profiles of several developers and enhance those objects with custom methods to process ...

What is the best way to hold off until a specific condition is met?

Seeking guidance as a newbie in the world of Protractor, I am currently attempting to implement an end-to-end test. However, facing some challenges as the page I wish to test is not entirely Angular-based. My initial spec looks like this: describe('s ...

Exploring the Depths of HTML with Jquery

This is an example of HTML code I am working with: <tr> <td> <div><span id="temp" /> </div> </td> </tr> <tr> <td> <div><span id="temp" /> </di ...

The debugger is currently in the process of disconnecting... - Node.js running in VSCode

I'm currently working my way through a JavaScript example in Visual Studio Code, but I've run into an issue with the debugger getting stuck while trying to disconnect. Running on macOS Sierra version 10.12.6 Using VSCode version 1.18.1 (latest ...