gpt4 book ai didi

javascript - 如何根据angularjs中的下拉值验证文本框?

转载 作者:行者123 更新时间:2023-11-28 04:00:19 24 4
gpt4 key购买 nike

在下拉菜单中我们有数字和小数

如果用户从下拉文本框中选择数字,则应允许仅输入数字(整数)例如 22,33,444,345436 。

不应允许输入十进制值 22.2,33.33,444.3333

如果用户从下拉列表中选择 Decimalnumber,则同一文本框应允许输入 2 个小数例子22.2,33.33,444.23

var app = angular.module('plunker', []);

debugger;

app.controller('MainCtrl', function($scope) {

$scope.selectedvalue = "Number";


$scope.userinput = "";

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>



<body ng-controller="MainCtrl">

please select
<select ng-model="selectedvalue">
<option value="Number">Number</option>
<option value="Decimalnumber">Decimalnumber</option>
</select><br>
<p>Selected: {{selectedvalue}}</p>

<input type="number" ng-model="userinput">

</body>

如何做到这一点,请帮助我..

最佳答案

首先你要改变:

<input type="number" ng-model="userinput">

 <input type="text" ng-model="userinput">

然后

var app = angular.module('plunker', []);


app.controller('MainCtrl', function($scope) {

$scope.selectedvalue = "Number";


$scope.userinput = "";

$scope.changeFun = function(e) {
var tempInput = document.querySelector("#inputId").value;
var regex = new RegExp("^[0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);

if($scope.selectedvalue === "Number") {
if ((regex.test(str) || e.which === 8)) {
return true;
}
e.preventDefault();
return false;
} else if($scope.selectedvalue === "Decimalnumber") {
var regex = new RegExp("^[0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if ((regex.test(str) || e.which === 8) && tempInput.indexOf(".") === -1) {
console.log("comming 1111");
return true;
}


if(tempInput.indexOf(".") === -1) {
return true;
}

if(tempInput.indexOf(".") !== -1 && str !== ".") {
var lastSubstr = tempInput.substring(tempInput.indexOf("."));
if (lastSubstr.length < 3)
{
return true;
}
}


e.preventDefault();
return false;
}

}
});

查看此链接:https://plnkr.co/edit/1fvI3grvZUzJCuqwJRXA?p=preview

关于javascript - 如何根据angularjs中的下拉值验证文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47173722/

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