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?
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.
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.
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.
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).
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With