3 зависимых выпадающих списков на Javascript - PullRequest
1 голос
/ 18 июня 2019

В предисловии я супер новичок в кодировании в целом. Это также первое веб-приложение, которое я разрабатываю на Google App Script.

Я модифицировал некоторый код, который, как я обнаружил, выполнил зависимое раскрывающееся меню до двух уровней (после выбора «страны» вы получите соответствующий список «состояний»).

Теперь я пытаюсь сделать так, чтобы после выбора «состояния» вы получали соответствующий список «критериев». Мне все равно, какая страна выбрана в этом случае, потому что каждый список критериев уникален для государства. Для этой цели я использую populateCriteria () в "page-js". это функция, над которой я изо всех сил пытаюсь работать ... t

Что-то, что я знаю:

  • Я знаю, что в первых двух выпадающих списках индексы использовались для сопоставления массивов ... для поиска по терминам мне нужно использовать Object () (например, если я выбираю состояние "Энергия", найдите список критериев, обозначенный как "Энергия"?) ( спасибо @Dustin Michaels )
  • Я использую materialcss. Я обнаружил, что это является помехой, когда дело доходит до раскрытия моих критериев после обновления
  • Я не могу просто выполнить поиск и сопоставление по критериям, потому что в некоторых штатах есть несколько вариантов для их критериев

Спасибо.

page.html

 <html>

    <body>
     <div class="row">


       <div class="col s6">
          <label>Category</label>    
          <select id="country" name ="country"></select> 
       </div>

       <div class="col s6">
        <label>Standard</label> 
        <select name ="state" id ="state" class="state"></select>
       </div>     

       <div class="col s12">
        <label>Criteria</label> 
        <select name ="criteria" id ="criteria" class="criteria"></select>  
       </div>   
    </div>

    <?!= include("page-js"); ?>

   </div> 
 </body>
</html>

page-js

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"</script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>    
   <script src="https://gumroad.com/js/gumroad.js"></script>

   <script>
     //Country= Cateogry, State=Standards     
      var country_arr = new Array("EOHS", "Quality", "FP&R");

     // States
     var s_a = new Array();
  s_a[0]="";
  s_a[1]="Energy|Personal Protective Equipment|Walking, Working Surfaces and Fall Protection|Machine Guarding|Electrical Safety|Minimum Safe Behaviors";
  s_a[2]="Documentation|Process Validation and Control|Equipment|Calibration|Product Conformance|Traceability|Documentation|Good Manufacturing Practice";
  s_a[3]="Sort Out (Organize)|Set in Order (Set Limits)|Shine (Cleanliness)|Standardize|Sustain";
  // <!-- -->

  //Criteria-- this should correspond to the standard selected
  var s_b = new Object();
  s_b['']="";
  s_b['Energy']="Energy Walk Abouts. Are there any air leaks, running equipment / with line down, air being used to control bottles, or any other opportunity to reduce energy consumption?";
  s_b['Personal Protective Equipment']="Are the personnel wearing the correct PPE? Safety glasses/shoes/hearing protection.  Is fall protection being utilized when working greater than 4ft above ground?  Scissor lift harness worn and tied off if feet leave floor, JLG harness worn and tied to anchor point at all times - 100% tie-off.";
  s_b['Walking, Working Surfaces and Fall Protection']="Are walking / working surfaces  free of debris and liquid?  No spills, wood, banding, preforms, etc. or other slip or trip hazards.";
  s_b['Machine Guarding']="Is there any missing or broken machine guards?  Are the guards securely in place?  No bolts /screws missing.  Is there evidence or did you witness bypassing or disabling machine guards or interlocks?";
  s_b['Electrical Safety']="Are electrical panels blocked or left open?  Are items left on panels?  Rags, tools, cleaning supplies, etc.";
  s_b['Minimum Safe Behaviors']="Did you witness personnel clearing a jam without stopping the machine?|Are LOTO locks located in close proximity to the machine?  Are employees performing maintenance without locking out the machine?|Are forklift seatbelts being used properly?  Are forklifts traveling at safe speed? Are forklifts traveling with empty forks less than 4 inches off ground?|Are ladders being used and stored properly? Maintain 3 points of contact, not standing at the top of a step ladder, ladder feet have rubber shoes.|Are machines/equipment/pipes, properly labeled?|Are product containers being used for purposes other than finished product?";
  // <!-- -->



  function populateCriterias(stateElementId ){

      var selectedStateIndex = document.getElementsById(stateElementId).selectedValue;

      var criteriaElement = {};

      criteriaElement.length=0; // Fixed by Julian Woods
      criteriaElement.options[0] = new Option('Choose the criteria','');
      criteriaElement.selectedIndex = 0;

      var criteria_arr = s_b[selectedStateIndex].split("|");


      for (var i=0; i<criteria_arr.length; i++) {
          criteriaElement.options[criteriaElement.length] = new Option(criteria_arr[i],criteria_arr[i]);
      }


    $("#" + stateElementId).formSelect();
  }


  function populateStates( countryElementId, stateElementId ){

      var selectedCountryIndex = document.getElementById( countryElementId ).selectedIndex;

      var stateElement = document.getElementById( stateElementId );

      stateElement.length=0;    // Fixed by Julian Woods
      stateElement.options[0] = new Option('Choose the standards','');
      stateElement.selectedIndex = 0;

      var state_arr = s_a[selectedCountryIndex].split("|");

      for (var i=0; i<state_arr.length; i++) {
          stateElement.options[stateElement.length] = new Option(state_arr[i],state_arr[i]);
      }

      // Assigned all states. Now assign event listener for the criteria.

        if( stateElementId ){
            stateElement.onchange = function(){
                populateCriterias(stateElementId );
            };
        }     
        $("#" + stateElementId).formSelect();
  }


    function populateCountries(countryElementId, stateElementId){
        // given the id of the <select> tag as function argument, it inserts <option> tags
        var countryElement = document.getElementById(countryElementId);
        countryElement.length=0;
        countryElement.options[0] = new Option('Choose the category','-1');
        countryElement.selectedIndex = 0;
        for (var i=0; i<country_arr.length; i++) {
            countryElement.options[countryElement.length] = new Option(country_arr[i],country_arr[i]);
        }

        // Assigned all countries. Now assign event listener for the states.

        if( stateElementId ){
            countryElement.onchange = function(){
                populateStates( countryElementId, stateElementId );
            };
        }
        $("#"+countryElementId).formSelect();
    }

    populateCountries("country", "state");

  </script>

1 Ответ

1 голос
/ 18 июня 2019

Я не могу полностью следовать тому, что вы делаете, но я думаю, что для этих s_b критериальных данных вы хотите использовать JavaScript объект вместо массива.

Массивы

Массив - это упорядоченный список значений, индексируемых целыми числами, такими как ваши s_a данные "состояний".

  s_a[1]="Energy|Personal Protective Equipment|Walking, Working Surfaces and Fall Protection|Machine Guarding|Electrical Safety|Minimum Safe Behaviors";

По индексу "1" вмассив s_a, вы найдете значение "Energy|Personal Protective Equipment...".

Объекты

объект - это структура данных, где ваши ключи могут быть значениями, кроме целых чисел, например строк,кажется, это то, что вы хотите сделать с вашими s_b «критериями» данных.Если вы объявите s_b как объект вместо массива, тогда вы можете использовать строки в качестве индексов или «ключей», как вы пытаетесь это сделать.

var s_b = {};

s_b['Energy']="Energy Walk Abouts. Are there any air leaks, running equipment / with line down, air being used to control bottles, or any other opportunity to reduce energy consumption?";

Затем вы можете посмотреть значение энергии, s_b['Energy'] и получите значение, которое вы установили "Energy Walk Abouts. Are there ....

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...