验证输入类型按钮最大值 9 和最小值 1 的功能,不起作用

Function to validate an input type button max value 9 and min value 1, not working

我有一个挑战,要根据输入的内容做出 table。

function createTable(){
    let table = document.getElementById('table')
    let row = document.getElementById('input-row').value
    let column = document.getElementById('input-column').value

     for(let rowIndex = 0; rowIndex < row; rowIndex++){
        let tr = document.createElement('tr')

        for(let colIndex = 0; colIndex < column; colIndex++){
            let td = document.createElement('td')
            tr.appendChild(td)
        }

        table.appendChild(tr)

        document.getElementById('input-row').value = " "
        document.getElementById('input-column').value = " "

        if(row == " ") {
            alert('Number of rows cannot be empty')
            return false
        }

        if(row > 9) {
            alert('Number of rows cannot be greater than 9')
            return false
        }

        if(row <= 0) {
            alert('Number of rows cannot be less than 1')
            return false
        }
      
    }
}
<div class="inputs-container">
            <div class="inputs-container_rows">
                <input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">
                <h3>Rows</h3>
            </div>
            <div class="inputs-container_columns">
                <input type="number" class="inputs" max=9 min=0 id="input-column">
                <h3>Columns</h3>
            </div>
 </div>
 <div class="btn-container">
            <button id="btn" onclick="createTable()">Create Table</button>
        </div>
        <div class="table-container">
            <table border="1" id="table">

            </table>
 </div>

为了验证,只有 if(row > 9) 有效,其他无效。

另外,我想在再次按下按钮时删除table,我不知道该怎么做。

我注意到一些问题:

  1. 因为您得到的 row 值是 string,您应该使用 String.length 属性 来检查它是否为空。或者您可以通过与 "".
  2. 进行比较来评估未输入任何值
  3. 比较前需要将row转为整数; parseInt() 方法可用于此目的。
  4. 您应该在循环之前评估条件。

let table = document.getElementById('table');
let rowElement = document.getElementById('input-row');
let columnElement = document.getElementById('input-column');

function isValid() {
    let row = rowElement.value;
    
    if(row.length == 0){
        alert('Number of rows cannot be empty');
        return false;
    }

    if(parseInt(row) > 9) {
        alert('Number of rows cannot be greater than 9');
        return false;
    }

    if(parseInt(row) <= 0) {
        alert('Number of rows cannot be less than 1');
        return false;
    }
    return true;
}

function createTable(){
    let row = rowElement.value;
    let column = columnElement.value;

    if(isValid(row))
    {
      for(let rowIndex = 0; rowIndex < row; rowIndex++)
      {
          let tr = document.createElement('tr')

          for(let colIndex = 0; colIndex < column; colIndex++){
              let td = document.createElement('td')
              tr.appendChild(td)
          }

          table.appendChild(tr);
          document.getElementById('input-row').value = "";
          document.getElementById('input-column').value = "";
      }
    }
}
<div class="inputs-container">
  <div class="inputs-container_rows">
      <input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">
      <h3>Rows</h3>
  </div>
  <div class="inputs-container_columns">
      <input type="number" class="inputs" max=9 min=0 id="input-column">
      <h3>Columns</h3>
  </div>
</div>

<div class="btn-container">
  <button id="btn" onclick="createTable()">Create Table</button>
</div>

<div class="table-container">
  <table border="1" id="table"></table>
</div>

如果您有任何需要用户交互的内容,您将需要监听事件(除非您正在使用 prompt(),但这简直太糟糕了)。 “click”事件是 goto 事件,但您可以使用更好的事件,特别是如果您使用 <form>。特别是一个事件是专门针对表格的:

  • submit:当用户专注于某个字段并点击 Enter/Return 键或 <button>, <input type="submit">,或 <input type="image"> 单击表格将:

    • 如果有任何 [required][pattern][min][max] 等属性或任何验证方法,则验证自身,

    • 从具有 [name] 属性的任何字段收集所有值,

    • 然后发送到服务器,会return响应。

如果没有服务器可将其发送到,它将 return 一个空白页面。下面的示例将在触发“提交”事件时执行所有操作,但不会将数据发送到服务器。您应该阅读以下内容:

详情在下面的例子中注释

/***********
    ** Creates a given element and appends them.
    * @param   {String}     tag     tagName of element to be 
    *                               created
    * @param   {DOM Object} parent  DOM object to append to
    * @param   {Number}     times   number of times tag is 
    *                               created
    * @param   {String}     content string in 
    *                               each cell (Default is empty)
    * @returns {DOM Object|Array} DOM object or an array of DOM 
    *                             objects
    */
    const setDOM = (tag, parent, times, content = '') => {
      let nodeList = [];
      for (let i = 0; i < times; i++) {
        let node = document.createElement(tag);
        parent.appendChild(node);
        node.insertAdjacentHTML('beforeEnd', content);
        nodeList.push(node);
      }
      return times > 1 ? nodeList : times === 1 ? nodeList.pop() : null;
    }
    
    /** Event handler passes an Event Object (e) **/
    const buildTable = e => {
    
      /** Event Properties/Methods 
      -Stop normal behavior of form submits
      -(io) is all form controls (fieldset, legend, input, 
      button)
      */
      e.preventDefault();
      const io = e.currentTarget.elements;
      
      /** Form Data 
      -(r) number of rows
      -(c) number of columns
      -(cnt) text if any from #edit
      */
      let r = parseInt(io.rows.value);
      let c = parseInt(io.cols.value);
      let cnt = io.edit.innerHTML;
      
      /** Create the Table 
      -Clear #box
      -Create <table> in #box
      -Create <tbody> in table
      */      
      io.box.replaceChildren();
      const table = setDOM('table', io.box, 1);
      const tB = setDOM('tbody', table, 1);
      
      /** Create Rows & Columns
      -Create all <tr>
      -if an array is returned...
        ...Use .forEach() to create the <td> for each <tr>...
        ...Otherwise just run setDOM() once to create the <td>
      */
      const allRows = setDOM('tr', tB, r);
      if (Array.isArray(allRows)) {
        allRows.forEach((row, idx) => setDOM('td', allRows[idx], c, cnt));
      } else {
        setDOM('td', allRows, c, cnt);
      }
      
      /** Create tHead 
      -if #head is checked...
        ...Create <thead>...
        ...Create <tr>...
        ...Create all <th>
      */
      if (io.head.checked) {
        let tH = table.createTHead();
        let hRow = setDOM('tr', tH, 1);
        setDOM('th', hRow, c, cnt);
      }
      
      /** Create tFoot 
      -if #foot is checked...
        ...Create <tfoot>...
        ...Create <tr>...
        ...Create all <td>
      */
      if (io.foot.checked) {
        let tF = table.createTFoot();
        let fRow = setDOM('tr', tF, 1);
        setDOM('td', fRow, c, cnt);
      }
    };
    
    // Reference the form and listen for the submit event
    const UI = document.forms[0];
    UI.onsubmit = buildTable;
*, *::before {box-sizing: border-box;}:root {font: 1ch/1.25 'Segoe UI';}body {font-size: 4ch;}.box {width: 100%;max-width: max-content;background: lightgrey;}.box:empty {border: 0;background: transparent;}.edit {width: 100%;min-width: 50vw;min-height: 50px;overflow-wrap: break-word;word-break: break-word;border: 0;outline: 0;padding: 0;}.group {display: flex;flex-flow: row wrap;justify-content: flex-start;align-items: center;}fieldset, button, input {border-radius: 4px;}input {display: inline-block;font-size: 100%;font-family: Consolas;}label {display: flex;align-items: center;margin-right: 2rem;margin-top: 4px;font-size: 100%;}label b {font-weight: 400;}button {display: block;float: right;width: 80px;margin: 4px 0;font-size: 100%;cursor: pointer;}.num {width: 5ch;}.chx {width: 15px;height: 15px;margin-bottom: -1px;cursor: pointer;}table {table-layout: fixed;border-collapse: collapse;width: 100%;}table, td, th {border: 1px solid #000;}th {background: lime;}tbody td {background: cyan;}tfoot td {background: tomato;}
<main>
    <form id='UI'>
      <fieldset>
        <fieldset class='group'>
          <legend>Rows &amp; Columns</legend>
          <label>Rows:......<sup>(max. 99)</sup>&nbsp;
          <input id='rows' class='num' type='number' min='1' max='99' maxlegnth='3' required></label>
          <label>Columns:.<sup>(max. 20)</sup>&nbsp;
          <input id='cols' class='num' type='number' min='1' max='20' maxlegnth='3' required></label>
        </fieldset>
        <fieldset>
          <legend>Optional text </legend>
          <fieldset id='edit' class='edit' contenteditable></fieldset>
        </fieldset>
        <fieldset class='group'>
          <legend>Optional Sections</legend>
          <label><b>Table Head:</b>&nbsp;<input id='head' class='chx' type='checkbox'></label>
          <label><b>Table Foot:</b>&nbsp;<input id='foot' class='chx' type='checkbox'></label>
        </fieldset>
        <button>GO</button>
        <fieldset id='box' class='box'></fieldset>
      </fieldset>
    </form>
  </main>