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

问题描述 投票:0回答:1

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

  <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",而且文本框中的值必须是每次搜索都是唯一的,而且当所有数字都显示时,它必须在文本框中显示 "No Coupon "的文本信息。

我使用下面的代码随机生成它,但我不能得到所需的结果.有人能帮助我吗?

Array.prototype.random = function (length) {
       return this[Math.floor((Math.random()*length))];
 }
// var randomcoupon = value.coupon.random(value.coupon.length);
html jquery arrays json random
1个回答
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" />
© www.soinside.com 2019 - 2024. All rights reserved.