I currently have a form in one of my applications which uses a hidden button as a fix for problems with the numeric keyboard on Android. Essentially, either pressing the enter key or focusing the button will submit the form.
Pressing enter works in Chrome (desktop), Firefox (desktop), and Safari (iOS) and only submits the form once. In IE, the browser is submitting the form twice, so I can only assume that it is focusing the submit button when the user presses enter.
Here's an example to demo this. In Chrome and other browsers I've tested, it will simply clear the box. In IE, it will alert for "Invalid quantity."
HTML:
<form data-bind="submit: SubmitQuantity">
Quantity:
<input id="quantity" type="number" data-bind="value: Quantity, valueUpdate: 'afterkeydown'"/>
<button type="submit" data-bind="event: { focus: SubmitQuantity }" class="hidden_button"></button>
</form>
CSS:
.hidden_button {
width: 0px;
height: 0px;
font-size: 0px;
border: 0px;
left: -9999px;
padding: 0px 0px 0px 0px;
}
JS:
var viewModel;
function ViewModel() {
var self = this;
self.Quantity = ko.observable('');
self.SubmitQuantity = function() {
if (isNaN(self.Quantity())) {
alert('Invalid quantity');
return;
}
self.Quantity(undefined);
};
}
viewModel = new ViewModel();
ko.applyBindings(viewModel);
Is there a way to prevent IE from doing this double submission that is caused by focusing the hidden field?
There isn't any really need to call your SubmitQuantity
function twice. Not exactly sure of your Android problems (maybe you could elaborate?), but I suspect you are using the hidden submit button to actually post the form. Using a submit
data-binding on a form
element will prevent the form from submitting . From the KO docs :
When you use the
submit
binding on a form, Knockout will prevent the browser's default submit action for that form. In other words, the browser will call your handler function but will not submit the form to the server. This is a useful default because when you use thesubmit
binding, it's normally because you're using the form as an interface to your view model, not as a regular HTML form. If you do want to let the form submit like a normal HTML form, just returntrue
from yoursubmit
handler.
So you could remove the hidden button entirely, and return true
in your SubmitQuantity
function when you are ready for the form to submit - in this example, it would be only after Quantity
is a number.
self.SubmitQuantity = function() {
if (isNaN(self.Quantity())) {
alert('Invalid quantity');
return false;
}else{
return true; // form will be submitted
}
self.Quantity(undefined);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.