How to prevent form submission

I am using KnockoutJS with SammyJS for a single page application.

In html, I have a form tag as follows

<form data-bind='submit: search'>
  <label>Find user:</label>
  <input data-bind='value: name' />
</form>

and in my view model, declared two functions and the sammy route url

function ViewModel() {
    var self = this;
    self.name = ko.observable("");
    self.search = function () {
      alert(self.name);
    };

    Sammy(function () {
        this.get('#:id', function () {
           //do something....
        });           
    }).run();
}

ko.applyBindings(new ViewModel());

All the code works fine until I type something in the text box, and then submit the form. I did not expect to see the URLs after the warning window, but the URL changed to something like this: "http: // localhost: 8258 / undefined?" my original url is "http: // localhost: 8258"

I doubted the urm sammy routing, so I removed the sammy code from the javascript code, then the url did not change after the warning window. Maybe I don’t understand how sammy works.

How to prevent URL change in this case?

+5
source
2

Sammy , .

<form action="#1234" method="post">

JS:

Sammy(function() {
    this.post('#:id', function() {
        // do something...

        return false; // avoid form submission
    });

    // ...
}).run();
+5

, . Sammy.js :

Sammy(function() {

    // Your routing.. 
    this.get('#:id', function () {
       //do something....
    }); 


    // Make Sammy.js leave the forms alone!
    this._checkFormSubmission = function(form) {
        return false;
    };

}).run();

:)

+3

All Articles