gpt4 book ai didi

javascript - 提交时的 Angular 验证

转载 作者:行者123 更新时间:2023-12-01 03:47:32 26 4
gpt4 key购买 nike

我正在尝试创建一个表单,如果您未填写任何字段,则在单击“提交”时将显示一条警报消息。我正在尝试使用 Angular 验证来实现这一点;然而,它根本不起作用。这是我目前拥有的代码:

(1) HTML 事件表单文件

  function mainController($scope, $http) {
$scope.formData = {};

$http.get('/api/events')
.success(function(data) {
$scope.events = data;
initMap(data);
for(i = 0; i < data.length; i++){
console.log(data[i].eventLocation);
//placeMarker(data[i]);
//test(data);
}
//placeMarker(data);
})
.error(function(data) {
console.log('Error: ' + data);
});

// when submitting the add form, send the text to the node API
$scope.createEvent = function() {
$http.post('/api/events', $scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.events = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}

// ATTEMPT AT FORM VALIDATION
$scope.validateForm = function() {
if (document.getElementById("inputName").value == "" || document.getElementById("inputType").value == "" || document.getElementById("inputLocation").value == "" || document.getElementById("inputDetails").value == "") {
alert("Please fill in all required fields!");
return false;
}
}
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="col-lg-6">
<!-- Validate form -->
<form name="myForm" onsubmit="return validateForm()">
<div class="form-group">

<label>Event Name</label>
<input type="text" name="inputName" class="form-control" ng-model="formData.eventName" placeholder="Event name">
</div>

<div class="form-group">
<label>Type</label>
<select class="form-control" id="inputType" ng-model="formData.eventType">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
</select>
</div>

<div class="form-group">
<label>Location</label>
<select class="form-control" id="inputLocation" ng-model="formData.eventLocation">
<option>Location 1</option>
<option>Location 2</option>
<option>Location 3</option>
</select>
</div>

<div class="form-group">
<label>Event Details</label>
<textarea class="form-control" name="inputDetails" ng-model="formData.eventDetails" rows="2" placeholder="Add details about your event"></textarea>
</div>
<div class="text-center">
<button id="add-event"type="submit" class="btn btn-primary" ng-click="createEvent()">Submit</button>
</div>
</form>

最佳答案

您可以使用ng-submit来做到这一点用于表单验证

<form name="myForm" ng-submit="validateForm()">

并用于验证使用 ng-model用于验证表单的变量

$scope.validateForm = function() { 
if (!$scope.formData.eventName || !$scope.formData.eventType ) {
alert("Please fill in all required fields!");
return false;

}

Demo

关于javascript - 提交时的 Angular 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43465663/

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