JSON获取从数组到文本输入html的唯一随机值,并在显示所有值时显示文本

时间:2020-06-11 09:51:53

标签: html jquery arrays json random

这是我的选项代码和文本框

  <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);
}

我需要的是在下拉列表中选择具有三个数字[“ 1”,“ 10”,“ 11”]的值“ First” 我需要在文本框中同时一次显示“ 1”,“ 10”或“ 11”。此外,每次搜索中文本框中的值都必须是唯一的,并且当显示所有数字时,它必须显示一条文本消息“否优惠券”。

我用下面的代码随机生成了它,但是我没有得到想要的结果。有人可以帮我吗?

Array.prototype.random = function (length) {
       return this[Math.floor((Math.random()*length))];
 }
// var randomcoupon = value.coupon.random(value.coupon.length);

1 个答案:

答案 0 :(得分:1)

一种方法是保留列表的引用(如下面提到的代码中的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" />

相关问题