html - JSON从数组到文本输入html获取唯一的随机值,并在显示所有值时显示文本
问题描述
这是我的选项代码和文本框
<select id="sel" class="form-control input-lg" data-live-search="true">
<option value="">-- Select Your Country--</option>
</select><br/><br/><br/>
<input type = "text" id = "txtName" class="form-control input-lg" />
</div>
这是我的 JSON 代码
[
{
"country":"First",
"coupon":["1","10","11"]
},
{
"country":"Second",
"coupon":"2"
},
{
"country":"third",
"coupon":"3"
},
{
"country":"fourth",
"coupon":"4"
},
{
"country":"fifth",
"coupon":"5"
}
]
我已将 JSON 填充到下拉列表并显示到文本(输入)框
$('#sel').append('<option value="' + value.coupon + '">' + value.country + '</option>');
$('#sel').change(function () {
var str = $("#sel").val();
$("#txtName").val(str);
}
我需要的是当我在下拉列表中选择值“First”时,它有 3 个数字 [“1”,“10”,“11”] 我需要一次显示“1”或“10”或“11”在文本框中随机。此外,文本框中的值在每次搜索时必须是唯一的,并且当显示所有数字时,它必须在文本框中显示文本消息“无优惠券”。
我使用下面的代码随机生成它,但我无法得到想要的结果。有人能帮帮我吗?
Array.prototype.random = function (length) {
return this[Math.floor((Math.random()*length))];
}
// var randomcoupon = value.coupon.random(value.coupon.length);
解决方案
一种方法是保留列表的引用(firstCouponOptions
如下面提到的代码中所示),每次从“文本框”中获取随机值并同时从列表中firstCouponOptions
删除该值。firstCouponOptions
当它为空时,显示“无优惠券”消息。
const options = [
{ "country": "First", "coupon": ["1", "10", "11"] },
{ "country": "Second", "coupon": "2" },
{ "country": "third", "coupon": "3" },
{ "country": "fourth", "coupon": "4" },
{ "country": "fifth", "coupon": "5" }
];
function getRandomValueFromList(list) {
const randomeIndex = Math.floor(Math.random() * (list.length));
return list[randomeIndex];
}
$(function() {
const firstCouponOptions = options[0].coupon;
options.forEach((value) => {
$('#sel')
.append('<option value="' + value.coupon + '">' + value.country + '</option>');
});
$('#sel').change(function() {
let str = $("#sel").val();
if ($("#sel option:selected").text() === 'First') {
if (firstCouponOptions.length) {
str = getRandomValueFromList(firstCouponOptions);
firstCouponOptions.splice(firstCouponOptions.indexOf(str), 1);
} else {
str = "No Coupon";
}
}
console.log(str);
$("#txtName").val(str);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel" class="form-control input-lg" data-live-search="true">
<option value="">-- Select Your Country--</option>
</select>
<input type="text" id="txtName" class="form-control input-lg" />
推荐阅读
- android - Android 10 Biometric API 总是回退到指纹
- python - 如何在python中使用webbrowser包自动打开html文件
- xcode - Xcode RealityKit / 无法为表达式生成诊断
- python - 如何使用 Tensorflow 对象检测 API 和 tf.estimator 执行自定义数据增强?
- elasticsearch - 如何从logstash中的一个索引中过滤出基于一个参数的记录
- sql - 重复广告商的 SQL 查询
- ios - 无法在 Firebase 存储上获取上传图片的网址
- javascript - 如何在 node.js 中创建会话变量并将其从路由传递到路由?
- c# - 将后端拆分为 2 个项目后的前端需求惊喜
- r - 在 valueBox 中添加 rho 作为图标