Vanishing Act: Backbone View Appears and Disappears

My Backbone.js view is created and inserted into a div element but it disappears after about a second.

Below is the code for my view:

var addPlayerView = Backbone.View.extend({
    tagName: "div",
    model: Player,
    id: 'addPlayerDiv',

    initialize: function() {
        console.log('addPlayerView has been created');
    },

    render: function (){
        this.$el.html('<p>show this puppy</p>');
        return this;
    }
});

Here is the model:

var Player = Backbone.Model.extend({
    defaults: {
        ID: "",
        firstName: '',
        lastName: ''
    },

    idAttribute: "ID"
});

And here is the HTML:

 <form onsubmit="addNewPlayer();">
        <input type="submit" value="Add New Player New"/>
 </form>

<p>
<div id="addPlayerDiv"></div>
</p>

<script>

        function addNewPlayer() {
            var player = new Player({});
            var newPlayerView = new addPlayerView({el: $("#addPlayerDiv"), model: player});
            newPlayerView.render();
        };

</script>

The addNewPlayer() function is correctly called and the newPlayerView renders on the page, but then it disappears quickly. Any suggestions on how to fix this issue?

Answer №1

To prevent the default action from occurring (such as onsubmit attempting to send data to the server), you can use the following methods:

<form onsubmit="addNewPlayer(); return false;">

or

<form onsubmit="addNewPlayer(event);">

function addNewPlayer(e) {
  e.preventDefault();
  .....
}

Here is an example.

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

Dealing with local JSON data asynchronously using ReactJS

Within my local workspace environment, there lies a valuable data.json file. Our application operates solely on the client side. I find myself torn between two potential methods of data consumption: import data from './data.json' // and start w ...

Exploring ways to retrieve a video thumbnail with VueJS3

I am currently working on a project to create a simple program that retrieves movies from my AWS-S3 bucket and transforms them into picture thumbnails. Below is the code I have written: <template> <img :src="imgURL" class="card- ...

Function on NextJS site failing to adhere to the two-second timeout limit

I have implemented an 'image slide show' that switches between images every two seconds by toggling their display types from "none" to "block". Within my .js file, the showSlides function is declared at the top: var slideIndex = 0; function sho ...

Is it possible to alter the appearance of my menu when clicked on?

Is there a way to update the appearance of an active menu or submenu that is selected by the user? I would like the chosen submenu and its parent menu to have a distinct style once clicked (similar to a hover effect, but permanent). /*jQuery time*/ $(do ...

employing rowspan functionality within a JavaScript application

How can I achieve a table layout where the first two columns are fixed for only one row and the remaining rows are repeated 7 times? Additionally, is there a way to make the bottom border of the last row thicker? Check out the expected table for reference. ...

What is the best way to verify the success or error callbacks of an AJAX request?

We have the option to include AJAX callback functions in various sections: $.ajax(url,{ data:data, ..., success:successCallback1, error:errorCallback1 }) .success(successCallback2) .error(errorCallback2) .done(successCallback3) .fail(errorCallb ...

Translate Latitude and Longitude values into X and Y coordinates on an Albers projection map

Trying to plot a point on a map with Albers projection using the given latitude and longitude coordinates, but encountering issues. The map is built with the Albers projection using standard parallels at 52 and 64 degrees with WGS 84. I attempted to imple ...

Best method for retrieving information from a string

Exploring different techniques to extract data from a string is a common practice, including methods like substring and split. Is there an optimal approach to accomplish this task? For instance, when faced with a URL structure such as http://myServer:8000/ ...

Encountering a JSON error with Backbone while attempting to retrieve data

I am having trouble using the Markit on demand Api for a stock search. Whenever I try to access the data through the API, I encounter an error that says "Uncaught SyntaxError: Unexpected token : " regarding the JSON response. The JSON provided in the error ...

When using multer to upload a file, the issue of req.files being undefined may

I am currently working on a Node.js Application using Express.js 4 that involves uploading an image. I opted to utilize the multer module for this task, but encountered an issue with accessing the uploaded file via req.files. Below is the relevant portions ...

Is it possible to display an HTML file along with accompanying JS files using Express in Node.js?

I am working with an index.html file and I need to send it using the following Node.js code: app.get('/', (req, res) => { res.sendFile(`${__dirname}/index.html`) }); Within the same directory, I also have some JavaScript files that I want ...

Highcharts encounters issues with dateRange values disappearing after a refresh in older versions of IE (9 and below) and Chrome

const newCurrentIndex = findIndexForCounter(currentPCData.CounterID, currentPCData.NetworkID); if (currentIndex === newCurrentIndex) { $.each(model.Data, (j, point) => { ...

Adding a clickable button to execute code within a LeafletJS marker!

I'm currently experimenting with adding a button inside a pointer that will log a message to the console. This is simply a test to see if I can execute a method on the marker, but so far I haven't been able to display any text. const marker = L.m ...

Retrieving information from a form that is generated dynamically

I successfully created a modal form dynamically/programmatically using bootstrap classes. However, I am facing an issue where I cannot access the data from the input boxes as there is no console.log() output. It seems like the form is not present in the DO ...

Is it possible to deploy a build across various website subdomains without altering user data?

Currently, I am in the midst of developing a project for a client where I am responsible for both the front end and back end components. After much consideration, I have opted to use Remix due to my familiarity with React and proficiency in JavaScript/Type ...

Detecting changes in arrays in Vue.js 2

Below is a simplified version of the code : <template> /* ---------------------------------------------- * Displaying a list of templates, @click to select the template /* ---------------------------------------------- <ul> ...

Sending the appropriate context using "this" to an external function within a class

Imagine a scenario where I have a simple class that extends other classes, and an object of functions that I am passing to class B const actions = { doSomething: (this: B, foo: boolean) => { console.log('from do something', this.text, ...

Modify the class of a div element depending on the value of a data attribute

I am faced with a situation where I have an iframe and two different sets of CSS codes - one for landscape orientation and one for portrait orientation. However, these are not specifically for the device's orientation but rather for the content loaded ...

My goal is to generate a collection of nested objects by iterating through an array and storing the results as input

I need help converting the elements in this array into a JSON object format. Here is the list of items in the array: Input var input = [ { bio: "Test", id: 2, image: "http://localhost:8000/media/default.jpg", user: 2 ...

Tips for retaining the value of a variable in JavaScript

I am a page that continuously redirects to itself, featuring next day and previous day arrows. Upon loading, the page always displays the new day. The days are stored in a localStorage as follows: for(var i = 0; i < status.length; i++) { local ...