Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent form submit

I am using KnockoutJS with SammyJS for one page application.

In the html I have form tag as follow

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

and in my viewmodel, declared two functions and 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 code works good, until I type something in textbox then submit the form. I expected no url browsing after alert window, but url is changed to something like this "http://localhost:8258/undefined?" my original url is "http://localhost:8258"

I doubted sammy url routing, so removed sammy code from javascript code, then url does not change after alert window. Maybe I do not understand how sammy works.

How to prevent url change it this case?

like image 777
Ray Avatar asked May 18 '12 12:05

Ray


People also ask

How do I block a form from submitting?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

How do you use Submit prevent?

Try @submit. prevent="myFunction()" , and your button could instead be <input type="submit" value="Submit"/> . The submit type will trigger the form to submit, and the submit. prevent will prevent the default submit behavior and execute myFunction as desired.

How do you prevent a form from reloading when submitting it?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.

How do I stop a form from submitting in PHP?

You can use exit() to stop PHP executing if you need to. Otherwise, you'll need to validate the form client-side using JavaScript (something you can find plenty of information about here or through Google).


1 Answers

Sammy binds itself to forms to enable you to register routes for them as well.

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

JS:

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

        return false; // avoid form submission
    });

    // ...
}).run();
like image 149
Niko Avatar answered Nov 15 '22 09:11

Niko