jurchiks jurchiks - 16 days ago 5
AngularJS Question

How to prevent form submit on enter key press using angular JS?

HTML:

<button class="btn btn-primary btn-xs" ng-click="toggleForm()">Add translation</button>
<form class="block form-inline" id="translation_form" ng-show="form" ng-submit="addTranslation()">
<h4>
Enter a new translation for this text in {{language | uppercase}}:
<button class="close" ng-click="toggleForm()" title="Close form">&times;</button>
</h4>
<hr />
<div class="form-group">
<input type="text" class="form-control" ng-model="formData.text" />
<button type="submit" class="btn btn-primary btn-sm">Add</button>
</div>
</form>


JS:

$scope.formData = {
text: ''
};

$scope.toggleForm = function()
{
if ($scope.form)
{
console.log('form closed', $scope.formData.text);
$scope.form = false;
$scope.formData.text = '';
}
else
{
$scope.form = true;

if ($scope.history
&& ($scope.history.length > 0))
{
// set some default text
$scope.formData.text = $scope.history[0].translation;
}

console.log('form opened', $scope.formData.text);
}
};

$scope.addTranslation = function()
{
console.log('adding translation', $scope.formData.text);
// ajax call to post the text
callback = function()
{
$scope.form = false;
$scope.formData.text = '';
}
};


The problem:
when I open the form, type some text and click on the "Add" button, the following texts are logged in the console:

form opened {some text here}
adding translation {some text here}


BUT if I open the form and tap Enter while focused on the input field, the following is logged:

form opened {some text here}
form closed {some text here}
adding translation {NO text here, because toggleForm empties the variable}


Obviously, this is a problem, since I want to be able to submit the form by tapping Enter aswell.
The question is - why is this happening and how to prevent it?




Edit: avoided the problem by changing the HTML structure to the following:

<div class="block" ng-show="form">
<h4>
Enter a new translation for this text in {{language | uppercase}}:
<button class="close" ng-click="toggleForm()" title="Close form">&times;</button>
</h4>
<hr />
<form class="form-inline" id="translation_form" ng-submit="addTranslation()">
<div class="form-group">
<input type="text" class="form-control" ng-model="formData.text" />
<button type="submit" class="btn btn-primary btn-sm">Add</button>
</div>
</form>
</div>


However, I still have no answer as to why AngularJS even called the close button's onclick event in the first place...

Answer

This response is a little late, but this issue just tripped my team up this afternoon - hopefully our experience will help others.

Merely adding attribute type="button" to your button object will do the trick - no need for any other changes. This is actually a good attribute to add to any button on your form that is not expressly a form submit button.

<button class="close" type="button" ng-click="toggleForm()" title="Close form">&times;</button>