首页 > 解决方案 > 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);

标签: htmljqueryarraysjsonrandom

解决方案


一种方法是保留列表的引用(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" />


推荐阅读