简体   繁体   中英

Select an option from a datalist and compare index number to another option in a second datalist

Sorry for the confusing title. What I have is two table columns next to each other, and in each are datalists . One is a list of course titles offered at a school, the other is the corresponding catalog numbers for the courses.

What I want to have happen is students can select the course title and it will automatically display the catalog number in the next column, or they can select the catalog number and it will display the course title in the previous column.

How I have this data set up currently is 2 separate arrays, like so:

<td>
    <input list="courses" name="course" placeholder="Course" onchange="indexTest()">
      <datalist id="courses">
       <!--Filled in script-->
      </datalist>
</td>
<td>
    <input list="catalogs" name="catalog" placeholder="Catalog Number">
      <datalist id="catalogs">
       <!--Filled in script-->
      </datalist>
</td>

    <script>
        var course = ["class 1","class 2","class 3","class 4","class 5"];
        var list = document.getElementById('courses');

        courseNames.forEach(function(item){
          var option = document.createElement('option');
          option.value = item;
          list.appendChild(option);
        });
    </script>

    <script>
        var catalog = ["catalog 1", "catalog 2","catalog 3","catalog 4","catalog 5"];
        var list = document.getElementById('catalogs');

        catNumbers.forEach(function(item){
          var option = document.createElement('option');
          option.value = item;
          list.appendChild(option);
    });
    </script>

I thought possibly I could run a script that looked up the index number of the selected option in one array and pulled the same index number from the other array, but I can't seem to get that to work.

If both arrays will have the corresponding values in the same indecies, you can just do this in your onchange events for each drop down:

Side note datalist is not supported in Safari or IE Version <= 9, may want to change to a select element:

<select id="courses" onchange="UpdateFromCourses()">

</select>

//Just make another function like this doing 
//the same thing but to the other drop down

 function UpdateFromCourses(){
    const selIndex = document.getElementById('courses').selectedIndex;
    document.getElementById('catalogs').selectedIndex = selIndex;
 }

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