gpt4 book ai didi

javascript - 如何防止使用 Angular JS 在输入键时提交表单?

转载 作者:行者123 更新时间:2023-11-30 06:59:17 25 4
gpt4 key购买 nike

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 = '';
}
};

问题:当我打开表单,键入一些文本并单击“添加”按钮时,以下文本将记录在控制台中:

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

但是,如果我打开表单并在专注于输入字段的同时点击 Enter,则会记录以下内容:

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

显然,这是个问题,因为我还希望能够通过点击 Enter 来提交表单。问题是 - 为什么会发生这种情况以及如何预防?


编辑:通过将 HTML 结构更改为以下内容避免了该问题:

<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>

但是,对于 AngularJS 为何首先调用关闭按钮的 onclick 事件,我仍然没有答案......

最佳答案

这个回复有点晚,但这个问题今天下午让我的团队陷入困境 - 希望我们的经验能帮助其他人。

只需向您的按钮对象添加属性 type="button" 即可解决问题 - 无需任何其他更改。这实际上是一个很好的属性,可以添加到表单上的任何按钮,但不是明确的表单提交按钮。

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

关于javascript - 如何防止使用 Angular JS 在输入键时提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23955895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com