我在表单上的TEXTAREA中有'n'个数字。用户在TEXTAREA中输入一些值后,我需要验证它与任何其他值的重复。
示例:
TEXTAREA_1 value =
10
20
30
40
10
它应该提醒并说'价值10被输入不止一次'。请帮助我使用JavaScript。
答案 0 :(得分:1)
var nums = textarea.value.split('\n').sort();
var prev;
for (var i = 0; i < nums.length; i++ ) {
if (prev && nums[i] == prev) {
alert('value ' + prev + ' was entered more than once');
break;
}
prev = nums[i];
}
答案 1 :(得分:0)
纯DOM / JS解决方案:
<form id="foo">
<textarea id="numbers-textfield" cols=40 rows=20>10
20
30
40
50
60
60</textarea>
<br>
<input type=submit value=submit>
</form>
<script>
(function() {
var form = document.getElementById('foo'),
textarea = document.getElementById('numbers-textfield'),
inArray = function( value, arr ) {
for ( var i = arr.length; i--; ) {
if ( value == arr[i] ) {
return true;
}
}
return false;
}
form.onsubmit = function() {
var value = textarea.value.split(/\s+/), len = value.length, stack = [], errors = false;
for ( var i = 0; i<len; ++i ) {
var isNum = !isNaN( value[i] );
if ( !isNum ) { continue; }
if ( errors ) { break; }
if ( !inArray( value[i], stack ) ) {
stack.push( value[i] );
} else {
errors = true;
alert( value[i] + ' already in stack');
}
}
if ( errors ) {
return false;
}
}
})();
</script>
答案 2 :(得分:0)
$(function() {
$("form").submit(function() {
var txt = $("#TEXTAREA_1");
var vals = txt.val().split("\n");
var len = vals.length;
for(var i = 0; i < len; i++) {
for(var j = i + 1; j < len; j++) {
if(vals[i] === vals[j]) {
alert("Duplicate values are not allowed");
txt.select();
return false;
}
}
}
});
});