Generate text input fields dynamically and store their values in an array using the Backbone.js framework

Is there a way to dynamically create text boxes based on a number input field with type='number'? Essentially, every time a user increments the number input, a new text box should be added to the backbone.js view. Additionally, when values are entered into these text boxes, I would like to store each value in an array within the backbone model. Here is a snippet of the code:

    <label for='choices'># Choices for Students</label>
    <input type='number' name='choices' step=1 />

    initialize: function(opts) {
    this.model = new QuestionCreateModel({
        mode: null,
        choices: ['A', 'B', 'C'],
        Question: "Question goes here",
        MaxChoices: 0,
        MinChoices: 0,
        WordLimit: 0,
        CharLimit: 0,
    }),

As you can see, I aim to use the number input field to populate the text boxes and assign values to the choices array in the Backbone model.

Thank you for any assistance provided!

-Stu

Answer №1

It looks like your code might be missing some key components.

First and foremost, you'll need to have a collection and a model set up.

Next, create your view and make sure it's set to listen for events like add, remove, change, or reset on the collection. By doing this, your view will be able to respond to these events and display the content as you intend it to.

myView = Backbone.View.extend({
   initialize : function() {
       this.collection = this.options.collection || new myCollection();
       this.collection.on("add remove reset change", this.render, this)
   },
   events : {
       "change [type='number']" : "numberChanged"
   },
   numberChanged : function(ev) {
       var $el = $(ev.target || ev.srcElement);
       var model = $el.data("model");
       model.set("selectedChoice", $el.val());
   },
   render : function() {
       this.$el.empty();
       this.collection.each(function(model) {
           $("<yourinput>").data("model", model)
               .appendTo(this.$el);
       }, this);
   }
});

Now, let's focus on setting up your Model and Collection.

var myModel = Backbone.Model.extend({
   initialize : function() {
      this.on("change:selectedChoice", this.onChoiceChanged, this);
   },
   onChoiceChanged : function(model,value) {
      // Once a value is selected, you can instruct the collection to create a new model
      if (this.collection) this.collection.push();
      // This action will trigger an "add" event, prompting your view to react and refresh.
   }
});

var myCollection = Backbone.Collection.extend({
   model : myModel
});

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

What could be causing issues with my jQuery POST call?

I am attempting to establish authentication with a remote service using jQuery. Initially, I confirmed that I can accomplish this outside of the browser: curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":" ...

Issue encountered while constructing my application (utilizing the "yarn run build" command and in Vercel)

Encountered an error during the build process, whether on the server or locally. This issue arises when using package managers like yarn, npm, and others. The error specifically points to a problem in the CSS file, but it only occurs in the production bu ...

Establish a React component to observe socket.io

I am currently looking for the best way to connect my React component with socket.io in order to listen to events. My current approach involves including the following HTML code: <script src="socket.io/socket.io.js"></script> and then initial ...

"Error encountered while attempting to make the entire row in AngularJS UI-Grid editable simultaneously

I am currently facing an issue while trying to make a whole row editable using ui-grid with AngularJs. If you could take a look at the coding in the provided plnkr link and let me know where I might have gone wrong, that would be really helpful. Click her ...

What is the best method for starting a string using the symbol '~'?

Hello everyone! I have a task that requires me to add a special feature. The user needs to enter something in a field, and if it starts with the tilde (~), all subsequent entries should be enclosed in a frame within the same field or displayed in a list ...

Tips for aligning text vertically in flexbox arrangements

As I work on building my portfolio, I have implemented links as buttons using flexbox to make responsiveness easier. The height of these flexboxes is set dynamically using JavaScript with percentages. Despite trying various suggestions, none of them provi ...

Creating a Comprehensive Page Design with Bootstrap and the Latest Version of Vue

My goal is to develop a Single Page Application using Vue3 and the Bootstrap 5 framework with a simple layout of Header -> Content -> Footer. I want the Content section to fill the space between the header and footer, ensuring there is no overlap. Ho ...

The node.js system automatically restarts an API call when a timeout occurs

Current Setup: I am using a combination of sails.js for the backend API and React for the frontend. The communication between the frontend and backend is handled by the fetch API. Scenario: Within some of my API endpoints, I need to run an external file ...

Transitioning from utilizing Jquery for post requests to implementing modern Promises

Currently, I am involved in a web application project that utilizes Flask and Python on the back-end with JavaScript on the front-end. I have been contemplating leveraging more modern styles like ES6/7 features such as Promises. In my development process, ...

The communication between a Firefox XUL extension and a webpage

Currently developing a Firefox XUL extension and in need of incorporating interaction between the web page and the extension. For instance, whenever a link is clicked on the page, I would like to trigger a function within the XUL extension. Is there any k ...

Tips for Setting Up Next.js 13 Route Handlers to Incorporate a Streaming API Endpoint via LangChain

I am currently working on establishing an API endpoint using the latest Route Handler feature in Nextjs 13. This particular API utilizes LangChain and streams the response directly to the frontend. When interacting with the OpenAI wrapper class, I make sur ...

Traversing through an array and populating a dropdown menu in Angular

Alright, here's the scoop on my dataset: people = [ { name: "Bob", age: "27", occupation: "Painter" }, { name: "Barry", age: "35", occupation: "Shop Assistant" }, { name: "Marvin", a ...

Removing Items from Orders

Stored in my MongoDB is the following JSON data: [ { "orderItems": [ "606808d2d7351b0c52d38634", "606808d2d7351b0c52d38635" ], "status": "Pending", ...

Failed Attempt to Execute React Native Application using Command Prompt (iOS)

I'm currently working through the React Native tutorial found on their official website. During my project building process, I utilized the following command: react-native run-ios An error was encountered: Found Xcode project TestProject.xcodeproj ...

What is the best approach to managing this scenario where the document is ready?

Just a quick question. I have several JavaScript functions written in this format: var app={ start:function(){ //do something and call calculate }, //end start calculate:function(){ //do more stuff } //end calculate }; //en ...

What is the best way to generate a nested object arrangement using a path (series of keys)?

I have a challenge of creating nested objects from arrays of strings to store the sequence of input strings. Originally, I was only generating chains with a depth of 2, but now I need to expand this capability to create higher-depth chains. Essentially, I ...

Using Slick.JS to Sync Navigation with Main Slider, Automatically Resetting to First Slide

I have a question about the functionality of the Slick.JS plugin that I'm using. In my project, I have two carousels with five slides each. The top carousel displays one slide at a time, while the bottom carousel shows all five slides concurrently. My ...

Is it possible for me to utilize this code for logging in through a dialog box?

Here is the code snippet I have on the client side: <p>Username:</p> <p><asp:TextBox ID="tbUsername" runat="server"></asp:TextBox></p> <p>Password:</p> <p><asp:TextBox ID="tbPassword" runat="server ...

Setting up the propTypes for interface in React TypeScript

How can I specify the correct PropTypes for a property that is an interface in TypeScript with PropTypes? Requirements - Implementing both TS and PropTypes. Goal - To have a more precise type definition than PropTypes.any that meets standard eslint an ...

The kendo-ui numeric textbox is malfunctioning when set with a step value of 0.001

Having some issues with the Kendo UI numeric text box. Specifically, it doesn't seem to work properly when using a step value of 0.001. In the example code snippet below, I managed to get it to increment by 0.001 with HTML5 but couldn't make it w ...