HTML 表单选择元素不允许更改

Posted

技术标签:

【中文标题】HTML 表单选择元素不允许更改【英文标题】:HTML Form Select Element Not Allowing Changes 【发布时间】:2022-01-23 23:55:28 【问题描述】:

我正在为我孩子的学校创建一个表单,但在选择学生姓名的下拉列表中遇到问题。该列表通过 javascript 代码填充,从关联的 google 表格中导入学生列表。我为每个选项添加了一个控制台日志,因为它们被创建以表明它们实际上正在被创建。 the link 上的开发者选项应该会显示这一点。

加载表格后,我无法从默认选项更改学生标识符。我不能说我做错了什么。如果我将这些值硬编码到 html 中,它可以正常工作,但我希望老师能够通过电子表格添加和删除学生,因为这是一种更加用户友好和灵活的实现方式。


form.html 代码

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <style>
      body 
        background: rgb(244, 235, 234)
      

      .outer-field 
        border-radius: 15px;
        background: white;
        height: 150px;
        margin: 10px;
        padding: 20px;
      

      .title 
        padding-left: 2%;
        font-weight: bold;
      
    </style>
  </head>
  <body>
  
    <div class="row">
      <div class="col s8 offset-s2 offset-s2">
        <!--Document Header-->
        <div class="outer-field" style="height: 100px">
          <h4>Golden Apple Reader Book Submissions</h4>
        </div>
        <!--Form to submit ISBN and autopopulate title and page count-->
        <form id="myForm" onsubmit="event.preventDefault(); formSubmit(this) ">
          <!--Creates ISBN entry field-->
          <div class="outer-field">
            <div class="title">Book ISBN</div>
            <div class="col s8">
              <div class="input-field">
                <input type="text" id="ISBN" name="ISBN" class="UUID validate" form="myForm">
                <label for="ISBN">ISBN</label>
              </div>
            </div>
            <!--Creates button to check ISBN data-->
            <button class="btn waves-effect waves-light" id="btn" style="margin-left: 3%" type="button" onclick="populateDetails(); return false;">Autofill Book Data From ISBN
              <i class="material-icons right">send</i>
            </button>
          </div> 
          
          <!--Creates student name entry field-->
          <div class="outer-field">
            <div class="title">Student Name</div>
            <div class="input-field col s12">
              <select form="myForm" name="StudentID" id="StudentID" required>
                <!--Add student IDs and names here-->
                <!--<option value="212702">John</option>
                <option value="212703">Henry</option>
                <option value="003">003</option>-->
              </select>
            </div>
          </div>

          <!--Creates book title entry field-->
          <div class="outer-field">
            <div class="title">Book Required Information</div>
            <div class="col s8">
              <div class="input-field">
                <input type="text" id="Title" name="Title" class="name" form="myForm" required>
                <label for="Title">Book Title</label>
              </div>
            </div>
          
          <!--Creates book page count entry field-->
            <div class="col s4">
              <div class="input-field">
                <input type="number" id="PageCount" name="PageCount" class="pages" form="myForm" required>
                <label for="PageCount">Book Page Count</label>
              </div>
            </div>
          </div>
          
          <!--Creates button to submit data-->
          <button class="btn waves-effect waves-light" type="submit" name="action" style="margin-left: 3%" >Submit
            <i class="material-icons right">send</i>
          </button>
        </form>        
      </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <script>      
      M.FormSelect.init(document.querySelectorAll('select'));
      
      //function to populate student list element
      (function () 
        google.script.run.withSuccessHandler(
          function (selectList) 
            var select = document.getElementById('StudentID');
            for( var i=0; i<selectList.length; i++ ) 
              //initial attempt commented here for troubleshooting
              //var option = document.createElement('option');
              //option.value = selectList[i][0];
              //option.text = selectList[i][4];
              var option = new Option(selectList[i][4], selectList[i][0]);
              console.log(option);
              select.add(option, undefined);
            
            console.log(select)
                      
        ).getSelectList();
      ());

      //Uses the ISBN to populate the book title and page quantity
      function populateDetails()
        isbn=document.getElementById('ISBN').value;
        //isbn=9781492680550;//for debugging only
        var url = "https://www.googleapis.com/books/v1/volumes?country=US&q=isbn:" + isbn;
        var obj
        var title="No Entry Identified";
        var pageCount=0;
        var titleout=document.getElementById('Title');
        var pageout=document.getElementById('PageCount');
        //fetches URL data from google books API
        fetch(url)
          .then(res => res.json())
          .then(data => obj = data)
          .then(
              function(settitle)
                //Assigns title to variable and text field
                title = obj.items[0].volumeInfo.title
                titleout.value=title;
                titleout.focus();
              ,
              function(titlerror)
              )
          .then(
            function(setpages)
              //Assigns page count to variable and text field
              pageCount = obj.items[0].volumeInfo.pageCount
              pageout.value=pageCount;
              pageout.focus();
            ,
            function(pageerror)
            )
        //In the case that no entry is found in google books API, assigns default values to text fields and deconflicts the overlapping label and value fields
        titleout.value=title;
        titleout.focus();
        pageout.value=pageCount;
        pageout.focus();
      
      
      //Submits form data to spreadsheet
      function formSubmit (data)         
        var dataToSubmit = 
          studentID: data.StudentID.value,
          title: data.Title.value,
          pageCount: data.PageCount.value
        
        //Provides a success message to the user
        google.script.run.withSuccessHandler(function () 
              myForm.reset()
              M.toast(html: "Thank you! You have successfully submitted!")
            ).submitData(dataToSubmit)
      

    </script>
  </body>
</html>

code.gs 代码

var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Submissions")
var ss2= SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Students")
var last=ss2.getLastRow();
var students=ss2.getRange(2,1,last-1,5).getValues();
function getSelectList() 
  try     
    return students;
  
  catch(err) 
    Logger.log(err);
  


function doGet() 
  return HtmlService.createTemplateFromFile('form').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')


function submitData (data)   
  ss.appendRow([new Date(),data.studentID, data.title, data.pageCount])


电子表格内容:

Student ID Number Student Name Teacher Name Grade Concatenation
UNK1 John TeacherA K Grade: K, Teacher: TeacherA, Name: John
UNK2 Henry TeacherA K Grade: K, Teacher: TeacherA, Name: Henry
UNK3 Paige TeacherA K Grade: K, Teacher: TeacherA, Name: Paige
UNK4 Raelyn TeacherA K Grade: K, Teacher: TeacherA, Name: Raelyn
UNK5 Danielle TeacherA K Grade: K, Teacher: TeacherA, Name: Danielle
UNK6 Olivia TeacherA K Grade: K, Teacher: TeacherA, Name: Olivia

【问题讨论】:

我建议您从一个只有一个选择的简单示例开始,然后尝试让它工作。 您应该提供minimal reproducible example 而不是整个项目。我认为这与材料有关。您可能应该在添加数据后启动或设置它。 ***.com/a/60365593/7215091 【参考方案1】:

当我看到你的脚本时,我认为有一个修改点。请进行如下修改。

发件人:

M.FormSelect.init(document.querySelectorAll('select'));

//function to populate student list element
(function () 
  google.script.run.withSuccessHandler(
    function (selectList) 
      var select = document.getElementById('StudentID');
      for( var i=0; i<selectList.length; i++ ) 
        //initial attempt commented here for troubleshooting
        //var option = document.createElement('option');
        //option.value = selectList[i][0];
        //option.text = selectList[i][4];
        var option = new Option(selectList[i][4], selectList[i][0]);
        console.log(option);
        select.add(option, undefined);
      
      console.log(select)
                
  ).getSelectList();
());

收件人:

//function to populate student list element
(function () 
  google.script.run.withSuccessHandler(
    function (selectList) 
      var select = document.getElementById('StudentID');
      for( var i=0; i<selectList.length; i++ ) 
        //initial attempt commented here for troubleshooting
        //var option = document.createElement('option');
        //option.value = selectList[i][0];
        //option.text = selectList[i][4];
        var option = new Option(selectList[i][4], selectList[i][0]);
        console.log(option);
        select.add(option, undefined);
      
      console.log(select)
      M.FormSelect.init(document.querySelectorAll('select')); // Moved.
    
  ).getSelectList();
());
在此修改中,M.FormSelect.init(document.querySelectorAll('select')) 已被移动。 我认为(function () ()); 可能不需要使用。

【讨论】:

以上是关于HTML 表单选择元素不允许更改的主要内容,如果未能解决你的问题,请参考以下文章

使用 Mobile Safari“表单助手”在选择元素上未触发更改事件

js 监测from表单中的input和select,时时监测,没有输入或选择信息报错,不允许提交数据

haha

Symfony2:使用 ajax 和验证更改选择

html 允许用户选择表单的电子邮件地址。此代码允许您在表单中设置“选择”字段,以允许用户设置

html 允许用户选择表单的电子邮件地址。此代码允许您在表单中设置“选择”字段,以允许用户设置