【问题标题】:Get 10 random checked checkboxes获得 10 个随机选中的复选框
【发布时间】:2021-03-30 23:04:35
【问题描述】:

我的问题是我想从 100 个复选框中选择大概 20 个,然后从所选的 20 个中随机选择 10 个。

我已经尝试过 Math.floor(Math.random() 但没有任何运气,如果可能的话,我无法弄清楚如何将两者结合起来

(这是我的第一个问题,希望你能帮忙。谢谢)

function getValue() {
  var checks = document.getElementsByClassName('checks');
  var str = 'Selected = ' + '<br>';


  for (i = 0;
    [i] < checks.length; i++) {
    if (checks[i].checked === true) {
      str += checks[i].value + ", " + "<br>";
    }
  }
  document.getElementById("Selected").innerHTML = str + "end";
}
<button onclick="getValue()">Click me</button>
<div class="prøve">
  <div class="option">
    <input type="checkbox" class="checks" value="film & animation" />
    <label>Film & Animation</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="science" />
    <label>Science & Technology</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="art" />
    <label>Art</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="music" />
    <label>Music</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="travel" />
    <label>Travel & Events</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="sports" />
    <label>Sports</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="news" />
    <label>News & Politics</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="tutorials" />
    <label>Tutorials</label>
  </div>
</div>

<div id="Selected">All Selected</div>

【问题讨论】:

  • label 元素应该与它们描述的元素相关联。这可以通过使用标签包装输入元素来实现,或者在输入上放置一个id,然后将该id-value 添加到标签的for-attribute 中。另外[i] &lt; checks.length 必须是i &lt; checks.length

标签: javascript html


【解决方案1】:

也许是这个?我正在使用这个 shuffle https://stackoverflow.com/a/12646864/295783

const shuffleArray = array => { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array }; // https://stackoverflow.com/a/12646864/295783

const getValue = () => {
  const checks = [...document.querySelectorAll('.checks:checked')];
  if (checks.length > 0)
    document.getElementById("Selected").innerHTML = `Selected = <br>
      ${shuffleArray(checks)
        .slice(0,10).map(chk => chk.value).join(", ")}`;
}
document.getElementById("getVal").addEventListener("click", getValue)
<button id="getVal">Click me</button>
<div class="prøve">
  <div class="option">
    <input type="checkbox" class="checks" value="film & animation" />
    <label>Film & Animation</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="science" />
    <label>Science & Technology</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="art" />
    <label>Art</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="music" />
    <label>Music</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="travel" />
    <label>Travel & Events</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="sports" />
    <label>Sports</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="news" />
    <label>News & Politics</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="tutorials" />
    <label>Tutorials</label>
  </div>
</div>

<div id="Selected">All Selected</div>

每个 div 一个

const shuffleArray = array => { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array }; // https://stackoverflow.com/a/12646864/295783

const getValue = () => {
  const checks = [...document.querySelectorAll('.checks:checked')];
  if (checks.length > 0) {
    const list = shuffleArray(checks).slice(0,10).map(chk => chk.value);
    document.getElementById("Selected").innerHTML = `Selected = <br>${list.join(", ")}`;
    list.forEach((val,i) => document.getElementById(`div${i}`).textContent = val);
  }  
}
document.getElementById("getVal").addEventListener("click", getValue)
<button id="getVal">Click me</button>
<div class="prøve">
  <div class="option">
    <input type="checkbox" class="checks" value="film & animation" />
    <label>Film & Animation</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="science" />
    <label>Science & Technology</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="art" />
    <label>Art</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="music" />
    <label>Music</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="travel" />
    <label>Travel & Events</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="sports" />
    <label>Sports</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="news" />
    <label>News & Politics</label>
  </div>

  <div class="option">
    <input type="checkbox" class="checks" value="tutorials" />
    <label>Tutorials</label>
  </div>
</div>

<div id="Selected">All Selected</div>
<div id="div0"></div>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<div id="div5"></div>
<div id="div6"></div>
<div id="div7"></div>
<div id="div8"></div>
<div id="div9"></div>

【讨论】:

  • 效果很好,正是我想要的。
  • 杜尔 velkommen
  • 我更新为添加一个连接,以便在值之间进行更整洁的分隔
  • 您是否知道如何在 10 个不同的 div 中取出 10 个随机数,以及我们目前在 1 个 div 中的 10 个随机数。所以相同的随机数不会重复?
  • 我的意思是,如果我想在 10 个不同的 div 中显示 10 个随机数。现在我们在 id 为 Selected 的 div 中显示 10 个随机数,但是如果我想在 id 为 Selected1 的 div 中获得 1 个随机数,然后在 id 为 Selected2 的新 div 中获得一个新的随机数呢?
【解决方案2】:

详情见内联cmets:

const randomAmount = 3; // How many do we want in the end?

let randoms = []; // Random checkbox references will go here
  
function getValue() {
  // Get all the selected checkboxes into a collection.
  // DO NOT use the legacy .getElementsByClassName() as it
  // returns a "live" node list that hinders performance.
  // Instead, use .querySelectorAll() and pass a selector that
  // gets you all checked checkboxes initially so you don't have
  // to loop and find them manually.
  var checks = document.querySelectorAll('.checks:checked');
  getRandoms(checks);  // Call out another function to get the randoms
  document.getElementById("Selected").textContent = randoms;
}

function getRandoms(checks){
  let gotThree = false;  // Starting value
  
  // Loop until you have 3 unique randoms
  while (!gotThree){
     // Get a random from 0 to 3
     let rnd = Math.floor(Math.random() * randomAmount); 
     
     // Is the random NOT already in the array?
     if(!randoms.includes(rnd)){
       // Add the checkbox that corresponds to that index
       randoms.push(checks[rnd]);
     }
     // Do we now have all the random checkboxes we wanted?
     if(randoms.length === randomAmount){
       gotThree = true;
       console.log(randoms);
     }
  }
}
<button onclick="getValue()">Click me</button>
<div class="prøve">
  <div class="option">
    <label>
    <input type="checkbox" class="checks" value="film & animation">
    Film & Animation</label>
  </div>

  <div class="option">
    <label>
    <input type="checkbox" class="checks" value="science">
    Science & Technology</label>
  </div>

  <div class="option">
      <label>
    <input type="checkbox" class="checks" value="art">
    Art</label>
  </div>

  <div class="option">
    <label>
    <input type="checkbox" class="checks" value="music">
    Music</label>
  </div>

  <div class="option">
    <label>
    <input type="checkbox" class="checks" value="travel">
    Travel & Events</label>
  </div>

  <div class="option">
    <label>
    <input type="checkbox" class="checks" value="sports">
    Sports</label>
  </div>

  <div class="option">
    <label>
    <input type="checkbox" class="checks" value="news">
    News & Politics</label>
  </div>

  <div class="option">
    <label>
    <input type="checkbox" class="checks" value="tutorials">
    Tutorials</label>
  </div>
</div>

<div id="Selected">All Selected</div>

【讨论】:

    【解决方案3】:

    shuffleArray 函数将对其进行洗牌并切片所有checked 输入,在此演示中,结果为3。将此数字更改为您的需要:arr.slice(0, 3);

    function getValue() {
      let val = [...document.querySelectorAll('.checks:checked')].map(c => c.value)
      
      shuffleArray(val).forEach(e => document.getElementById("Selected").innerHTML += "<br>" + e)
    }
    
    
    function shuffleArray(arr) {
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
      return arr.slice(0, 3);
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Checkbox</title>
    </head>
    
    <body>
    
      <button onclick="getValue()">Click me</button>
      <div class="prøve">
        <div class="option">
          <input type="checkbox" class="checks" value="film & animation" />
          <label>Film & Animation</label>
        </div>
    
        <div class="option">
          <input type="checkbox" class="checks" value="science" />
          <label>Science & Technology</label>
        </div>
    
        <div class="option">
          <input type="checkbox" class="checks" value="art" />
          <label>Art</label>
        </div>
    
        <div class="option">
          <input type="checkbox" class="checks" value="music" />
          <label>Music</label>
        </div>
    
        <div class="option">
          <input type="checkbox" class="checks" value="travel" />
          <label>Travel & Events</label>
        </div>
    
        <div class="option">
          <input type="checkbox" class="checks" value="sports" />
          <label>Sports</label>
        </div>
    
        <div class="option">
          <input type="checkbox" class="checks" value="news" />
          <label>News & Politics</label>
        </div>
    
        <div class="option">
          <input type="checkbox" class="checks" value="tutorials" />
          <label>Tutorials</label>
        </div>
      </div>
    
      <div id="Selected">All Selected</div>
    
    </body>
    <script src="Checkbox.js"></script>
    
    </html>

    【讨论】:

    • 这与我的代码相同,只是您的 DOM 更新处于循环中并且您使用 c 而不是 chk
    • @mplungjan 完全相同但不完全相同 ;) 还有更多差异,我更喜欢我的,它更干净。随机播放是一样的,我只是切片返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多