显示任何数字输入的数据



我得到了适用于预定义数字(100200(的代码,但我想让它适用于任何随机的6位数字。输出保持不变。

我想在用户输入从 000000 到 999999 的任何 6 位代码时,以给定格式显示英国伦敦的输出。

我该怎么做呢?

const $main = $('#zipcode');
const $inputs = $('.location');
const values = {
trigger: '100200',
birds: ['London', 'England']
};
$main.on('keyup', function() {
if (this.value === values.trigger) {
$inputs.each(function(i, el) {
el.value = values.birds[i];
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="number" id="zipcode" class="form-control" required>
<hr />
<input type="text" id="location1" class="location" required>
<input type="text" id="location2" class="location" required>

你只需要用this.value.toString().length === 6替换this.value === values.trigger

这将检查输入数是否等于 6,而不考虑输入的实际内容。

const $main = $('#zipcode');
const $inputs = $('.location');
const values = {
trigger: '100200',
birds: ['London', 'England']
};
$main.on('keyup', function() {
if (this.value.toString().length === 6) {
$inputs.each(function(i, el) {
el.value = values.birds[i];
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="number" id="zipcode" class="form-control" required>
<hr />
<input type="text" id="location1" class="location" required>
<input type="text" id="location2" class="location" required>

我们可以在修剪输入值后检查输入值的长度(只是为了避免多余的空格(并验证输入是否为整数值。

const $main = $('#zipcode');
const $inputs = $('.location');
const values = {
trigger: '100200',
birds: ['London', 'England']
};
$main.on('keyup', function() {
var thisValue = (this.value).trim();
if (thisValue.length == 6 && !isNaN(thisValue)) {
$inputs.each(function(i, el) {
el.value = values.birds[i];
});
}
});

const $main = $('#zipcode');
const $inputs = $('.location');
const values = {
trigger: '100200',
birds: ['London', 'England']
};
$main.on('keyup', function() {
if (this.value.length >= 6 && this.value >=0 && this.value <= 999999) {
$inputs.each(function(i, el) {
el.value = values.birds[i];
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="number" id="zipcode" class="form-control" required>
<hr />
<input type="text" id="location1" class="location" required>
<input type="text" id="location2" class="location" required>

您可以将条件更改为

if (this.value.toString().length === 6) 

它只是检查数字是否有 6 位数字。

在 if 条件下尝试此操作 =

if (this.value >= 0 || this.value <=999999) {

试试这段代码:

const $main = $('#zipcode');
const $inputs = $('.location');
const values = {
trigger: '100200',
birds: ['London', 'England']
};
$main.on('keyup', function() {
if (Number.isInteger(this.value)) {
if(this.value>=000000 && this.value<= 999999){
$inputs.each(function(i, el) {
el.value = values.birds[i];
});
}    
}
});

最新更新