简体   繁体   中英

loop to check combination of dropdown & checkbox in pure javascript

Good morning. I have a page with 1 dropdown menu that has 24 options to select. As well There are 12 checkboxes to select. Each dropdown option and each checkbox has a predefined variable. ie:: dropdown value="utcValue0 -> var utc0 and checkbox value id="gameCheck" -> var gameTag desired output here is a new variable var a = utc0 + gameTag ;

My current solution works, however it is very tedious and terrible to read and there must be a whole lot easier way to handle this. I'm at the moment just defining each scenario 1 by 1. Considering it's 24 dropdown menus and 12 checkboxes this can not be the way.. I think it can be done with a smart nested loop, but I can't come up with how to actually write that.

I'd highly appreciate some help! Thank you so much!

    <select name="hourSelector" id="hourSelectorID">
      <option value="utcValue0">0 - 1 UTC</option>
      <option value="utcValue1">1 - 2 UTC</option>
      <option value="utcValue2">2 - 3 UTC</option>
      <option value="utcValue3">3 - 4 UTC</option>                
      <option value="utcValue4">4 - 5 UTC</option>
      <option value="utcValue5">5 - 6 UTC</option>
    </select>

       <input type="checkbox" class="custom-control-input" id="gameCheck">
       <input type="checkbox" class="custom-control-input" id="purchCheck">
       <input type="checkbox" class="custom-control-input" id="inputCheck">
    var utc0 = 'something';
    var utc1 = 'something';
    var utc2 = 'something';
    var utc3 = 'something';
    var utc4 = 'something';
    var utc5 = 'something';
    //var utcX = 'created>"' + todayUTC + 'T00:00:00Z"' + ' ' + 'created<"' + todayUTC + 'T01:00:00Z"';

var gameTag = 'whatever';
var purchTag = 'otherwhatever';
var eventTag = 'morewhatver';

  // grab input Hour
  var hourDropdown = document.getElementById("hourSelectorID");
  var selectedHour = hourDropdown.options[hourDropdown.selectedIndex].value;

    if (document.getElementById('gameCheck').checked) {
      if (selectedHour == 'utcValue0' ) {
        var a = utc0 + eventTag
      }
      if (selectedHour == 'utcValue1') {
        var a = utc1 + eventTag
      }
      if (selectedHour == 'utcValue2') {
        var a = utc2 + eventTag
      }
      if (selectedHour == 'utcValue3') {
        var a = utc3 + eventTag
      }
      if (selectedHour == 'utcValue4') {
        var a = utc4 + eventTag
      }
      if (selectedHour == 'utcValue5') {
        var a = utc5 + eventTag
      }
    }  

You have changed your question so I'm not sure with what follows. Drop a comment below for adjustments or questions:-)

 var formEl = document.getElementById("form"); var selectEl = document.getElementById("hourSelectorID"); var checkboxEls = Array.prototype.slice.call( document.getElementsByClassName("custom-control-input") ); // option elements for (let i = 0; i < 24; i++) { let optionEl = document.createElement("option"); optionEl.value = "utcValue" + i; optionEl.textContent = i + " - " + (i + 1) + " UTC"; selectEl.appendChild(optionEl); } // form submit formEl.addEventListener("submit", function (ev) { ev.preventDefault(); console.log(toStringStuff()); }); // rename as needed:-) function toStringStuff () { var now = Date.now(); // in ms var hourInMs = 1000 * 60 * 60; var dayInMs = hourInMs * 24; var today = now - now % dayInMs; // `now` with time set to 0 var i = selectEl.selectedIndex; // hours to add to `today` var dt0 = new Date(today + i * hourInMs).toISOString(); var dt1 = new Date(today + (i + 1) * hourInMs).toISOString(); var utc = 'created>"' + dt0 + ' ' + 'created<"' + dt1; return [utc].concat(checkboxEls.filter( function (el) { return el.checked; } ).map( function (el) { return el.value; } )).join(" "); }
 <form id="form"> <select id="hourSelectorID" name="hourSelector" ></select> <label><input id="gameCheck" type="checkbox" class="custom-control-input" value="gameTag" checked > Game Check</label> <label><input id="purchCheck" type="checkbox" class="custom-control-input" value="purchTag" checked > Purch Check</label> <input type="submit"> </form>

Here is a solution taking advantage of the options indexes matching the itteration of the string. It takes the index of the selected option and changes the string accordingly while concatenating the values from selected checkboxes.

 let dateUTC = new Date(); let todayUTC = dateUTC.getUTCFullYear() + '-' + (('0' + dateUTC.getUTCMonth()+1)).slice(-2) + '-' + ('0' + dateUTC.getUTCDate()).slice(-2); const select = document.querySelector("#hourSelectorID"); const allCheckboxes = document.querySelectorAll('input[name="chkBox"]'); const elements = [select, ...[...allCheckboxes]]; elements.forEach(el => { el.addEventListener("change", () => { let checkedValues = [] const checked = [...allCheckboxes].filter(cb => cb.checked); checked.forEach(cb => checkedValues.push(cb.value)) console.log(`created>" ${todayUTC} T0${select.selectedIndex}:00:00Z" created<" ${todayUTC} T0${select.selectedIndex+1}:00:00Z" ${checkedValues.join(' ')}`) }); });
 <select name="hourSelector" id="hourSelectorID"> <option value="utcValue0">0 - 1 UTC</option> <option value="utcValue1">1 - 2 UTC</option> <option value="utcValue2">2 - 3 UTC</option> <option value="utcValue3">3 - 4 UTC</option> <option value="utcValue4">4 - 5 UTC</option> <option value="utcValue5">5 - 6 UTC</option> </select> <input value="whatever" type="checkbox" name="chkBox" class="custom-control-input" id="gameCheck"> <input value="otherwhatever" type="checkbox" name="chkBox" class="custom-control-input" id="purchCheck"> <input value="morewhatver" type="checkbox" name="chkBox" class="custom-control-input" id="inputCheck">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM