Having trouble getting the Bootstrap modal form to submit when using Knockout's submit binding?

Check out my jsFiddle example by clicking here.

I am currently working on a form within a bootstrap modal. The problem I'm facing is that the knockout submit binding doesn't get executed unless the user clicks on the submit input. It seems like bootstrap might be interfering with the knockout binding, but I'm not sure how to resolve this issue.

Pressing the enter key closes the modal dialog without executing the binding function (which means I can't send the data). However, clicking on the submit input triggers the binding as expected.

Below is the excerpt of relevant code:

Script:

function ArticleViewModel() {
    var self = this;

    self.SendArticleName = ko.observable('');
    self.SendArticleEmail = ko.observable('');

    self.SendArticle = function() {
        $.ajax('http://example.com', {
            data: ko.toJSON({ name: self.SendArticleName, email: self.SendArticleEmail }),
            type: "post", contentType: "application/json",
            success: function(result) {
                $('#share-modal').modal('hide');
            }
        });
    };

}

var articleViewModel = new ArticleViewModel();

ko.applyBindings(articleViewModel);

HTML:

<div id="share" class="row article-section">
    <div class="span12">
        <h4>Share</h4>
        <a class="btn btn-large" role="button" data-toggle="modal" href="#share-modal"><i class="icon-envelope"></i> Share This Article</a>

        <div id="share-modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <form class="form-horizontal" data-bind="submit: SendArticle" class="modal-form">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h3 id="myModalLabel">Share</h3>
                </div>
                <div class="modal-body">
                    <p>Who would you like to send the article to?</p>
                    <br />
                        <div class="control-group">
                            <label class="control-label">Name</label>
                            <div class="controls">
                                <input type="text" placeholder="Name" data-bind="value: SendArticleName" />
                            </div>
                        </div>

                        <div class="control-group">
                            <label class="control-label">Email</label>
                            <div class="controls">
                                <input type="text" placeholder="Email" data-bind="value: SendArticleEmail" />
                            </div>
                        </div>
                </div>
                <div class="modal-footer">
                    <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
                    <input type="submit" value="Send" />
                </div>
            </form>
        </div>
    </div>
</div>

Answer №1

The issue arises because the first button in the form is automatically set as the default, causing your cancel button to be triggered when you press Enter.

Check out this thread on Stack Overflow for some possible solutions: Multiple submit buttons on HTML form – designate one button as default

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

Analyzing length of strings by dividing content within div tags using their unique ids

Here's my issue: I'm using AJAX to fetch a price, but the source from where it is fetched doesn't add a zero at the end of the price if it ends in zero. For example, if the price is 0.40 cents, it comes back as 0.4. Now, my objective is to t ...

I would like to terminate the property when processing it on a mobile device

<div class="col-sm-24 embed-responsive"> <iframe width="100%" src="http://www.youtube.com/embed/${item.snippet.resourceId.videoId}"></iframe> </div> .embed-responsive iframe { height: 185px; margin-top: -4%; paddin ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

Passing an event from onSubmit in React without using lambdas

Within our current project, the tslint rule jsx-no-lambda is in place. When attempting to capture event from onSubmit, this is how I typically write my code: public handleLogin = (event: React.FormEvent<HTMLFormElement>) => { event.preventDe ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

Connects URLs to the displayed outcomes in jQuery Auto-suggest Interface

This particular code snippet has been modified from a tutorial on jQuery autocomplete <!doctype html> <html lang="en> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

Executing JavaScript code within ASP.NET Visual Basic

My current web application uses jQuery and JavaScript, but I want to add more features that are supported in ASP.net VB. However, I am unsure if the JavaScript can run after the VB code. Essentially, I would like the web app to follow this sequence: ...

Encountering an Unexpected Token Error While Parsing JSON with jQuery

Utilizing the Envato API with jQuery to collect user stats is my current project. An example JSON response that I will display is as follows: { "new-files-from-user":[ { "thumbnail":"http://3.s3.envato.com/files/60560.jpg", "tags":"", "use ...

The split function of a string displays an undefined result

My goal is to extract all characters that come after the equal sign within a URL: let url = this.$route.query.item console.log(typeof(url)) // outputs string let status = url => url.split('=')[1] When I run the code, it shows &apo ...

Unable to assign value to a public variable in Angular

I am facing an issue where I am trying to retrieve a value from the localStorage and assign it to a variable. However, when I try to use that variable in functions, it is coming up as undefined. code export class DashboardService { public token: any; ...

Delaying the call of a JavaScript function with jQuery

Basic JavaScript Function: $(document).ready(function(){ function sampleFunction() { alert("This is a sample function"); } $("#button").click(function(){ t = setTimeout("sampleFunction()",2000); }); }); HTML ...

Raphael and jQuery/JavaScript for user-selected array intersections

Hello everyone! This is my first time posting here, and I must say that I'm still quite new to JavaScript/jQuery/Raphael. Please forgive me if I make any mistakes or ask basic questions. :) I've been searching high and low for answers to my quer ...

Stopping all animations with JQuery animate()

I have a question about stopping multiple animations. Here's some pseudocode to illustrate my situation: CSS #div1 { position: absolute; background-image: url("gfx/cat.jpg"); width: 60px; height: 70px; background-size: 50%; b ...

Learn how to implement Basic Authentication in your Express application using the express-basic-auth package. You can easily trigger login and logout

When it comes to logging out a user who has logged in using basic Auth, I am exploring different options by consulting various sources like: link1 link2 In my application, I have implemented express-basic-auth to secure certain routes. Here is an example ...

Tips for utilizing code submitted by a user to extract meaningful errors

As I work on developing a mod for the online game Cookie Clicker, I've implemented a feature that allows users to input their own code to enhance the functionality of my mod. However, before users save their code using my custom editor, I want to run ...

I am experiencing a JSON parse error while making an AJAX request after upgrading to Codeigniter 3.x. What could be the reason behind this

I am currently in the process of updating my Codeigniter framework from version 2.2.6 to 3.0.6, and unfortunately, this update has caused some previously working code to break. One specific error that I am encountering is "SyntaxError: JSON.parse: unexpect ...

New to using JavaScript and JQuery, attempting to position a form underneath an image at a specific URL for the

Hello, I'm having difficulties placing a form below an image with a specific URL. As someone who is still learning JQuery, I am unsure of what mistake I might be making. Is there anyone who can help me figure out what's wrong here? <html> ...

Cryptocurrency price tracker with sleek Bitcoin symbol and FontAwesome icons

My assignment involved creating a function that retrieves Bitcoin trades from a JSON URL, allows users to change the interval with buttons, uses fontawesome arrows to indicate rate changes (up/down/no change), and displays the data on a website. Everythin ...

Tips for transferring a jQuery array to PHP

I am encountering an issue when trying to send a jQuery array to PHP. Initially, I have one form in HTML and upon clicking 'add', I end up with two forms. Afterwards, I input data into the form which is then stored in a jQuery array. However, I a ...

What is the process for obtaining the hashed password to store in my database?

Despite being able to run a test in Postman, I am facing difficulties with passing my hashed password into the DB correctly. const express = require("express"); // const helmet = require("helmet"); const { User } = require("./db/mo ...