一旦计算出第一行值,就启用表中的所有其他行

时间:2019-03-24 07:07:44

标签: javascript html

这些是一些简单的JS代码,使我能够在计算出第一行的值后启用其余的表行。

当我加载/刷新页面时,第一行启用了用户输入/自动计算。表中的其余行均被禁用。输入表中的第一行并显示所有值后,我希望启用表中的其余行,并希望通过一些计算以新的方式显示新值。

我正在尝试编写一个使用"onmouseover=func();"调用的函数,我似乎无法正确理解JS代码。有什么想法吗?

我理想的工作目标是编写一个代码,该代码可以确定是否存在表第一行中的所有值,然后启用表行的其余部分。

我知道这听起来很简单,但是我可以使用一些帮助,因为这是我第一次使用JS。谢谢你的想法。

请参阅代码部分。我有一个带有嵌入式CSS样式的HTML文件。 我已经创建了一个JS脚本。

最终产品是为LabArchive Research Notebook制作一个小部件。

用于初始启用和禁用的代码是在加载小部件时在HTML文件中完成的。

<style type="text/css">table {
                border-collapse: collapse;
                border: 3px solid purple;;
                cellpadding: 1px;
                cellspacing: 1px;
                width: 930px;
                height: 100px;
                font-family: Times;
            }

            input[type=text]:enabled {
                background: #19aeff;
            }

            input[type=text]:disabled {
                background: #dddddd;
            }
</style>
<table id="T01">
    <thead>
        <tr>
            <th scope="col" style="width: 35px;"><strong>Substance</strong></th>
            <th scope="col" style="width: 8px;"><strong>Amount<br />
            (mg)</strong></th>
            <th scope="col" style="width: 8px;"><strong>FW<br />
            (g/mol)</strong></th>
            <th scope="col" style="width: 8px;"><strong>Moles<br />
            (mmol)</strong></th>
            <th scope="col" style="width: 5px;"><strong>Equiv.</strong></th>
            <th scope="col" style="width: 8px;"><strong>Volume<br />
            (uL)</strong></th>
            <th scope="col" style="width: 5px;"><strong>Density<br />
            (g/mL)</strong></th>
            <th scope="col" style="width: 35px;"><strong>Comments</strong></th>
        </tr>
    </thead>
    <tbody>
        <tr id="R02">
            <th scope="col" style="text-align: left; width: 35px;"><input maxlength="30" name="substance1" size="35" type="text" value="Oxygen" /></th>
            <td scope="col" style="text-align: right; width: 8px;"><input name="amount1_number" size="8" type="text" /></td>
            <th scope="col" style="text-align: right; width: 8px;"><input name="fw1_number" size="8" type="text" /></th>
            <th scope="col" style="text-align: right; width: 8px;"><input name="moles1_formula" size="8" type="text" value="(#{amount1_number}/#{fw1_number}).toFixed(2)" /></th>
            <th scope="col" style="text-align: right; width: 5px;"><input name="equivalents1_number" size="5" type="text" value="1" /></th>
            <th scope="col" style="text-align: right; width: 8px;"><input name="volume1_formula" size="8" type="text" value="(#{amount1_number}/#{density1_number}).toFixed(2)" /></th>
            <th scope="col" style="text-align: right; width: 5px;"><input name="density1_number" size="5" type="text" /></th>
            <th scope="col" style="text-align: right;"><input maxlength="100" name="comments1" size="35" type="text" value="Sample Test Value" /></th>
        </tr>
        <tr>
            <th scope="col" style="text-align: left; width: 35px;"><input disabled="disabled" name="substance2" size="35" type="text" /></th>
            <td scope="col" style="text-align: right; width: 8px;"><input disabled="disabled" name="amount2_number" size="8" type="text" value="" /></td>
            <th scope="col" style="text-align: right; width: 8px;"><input disabled="disabled" name="fw2_number" size="8" type="text" /></th>
            <th scope="col" style="text-align: right; width: 8px;"><input disabled="disabled" name="moles2_formula" size="8" type="text" value="(#{moles1_formula}*#{equivalents2_number}).toFixed(2)" /></th>
            <th scope="col" style="text-align: right; width: 5px;"><input disabled="disabled" name="equivalents2_number" size="5" type="text" /></th>
            <th scope="col" style="text-align: right; width: 8px;"><input disabled="disabled" name="volume2_formula" size="8" type="text" value="(#{amount2_number}/#{density2_number}).toFixed(2)" /></th>
            <th scope="col" style="text-align: right; width: 5px;"><input disabled="disabled" name="density2_number" size="5" type="text" /></th>
            <th scope="col" style="text-align: right;"><input disabled="disabled" name="comments2" size="35" type="text" /></th>
        </tr>
    </tbody>
    <script>

</script>
</table>

<p>&nbsp;</p>


my_widget_script =
    {
      init:function (mode, json_data) {
        //this method is called when the form is being constructed
        // parameters
        // mode = if it equals 'view' than it should not be editable
        //        if it equals 'edit' then it will be used for entry
        //        if it equals 'view_dev' same as view,  does some additional checks that may slow things down in production
        //        if it equals 'edit_dev' same as edit,   does some additional checks that may slow things down in production

        // json_data will contain the data to populate the form with, it will be in the form of the data
        // returned from a call to to_json or empty if this is a new form.
        //By default it calls the parent_class's init.

        //TO DO write code specific to your form
        console.log('Welcome to stoichiometry world today!')
        console.log('Hello World  - q')

        this.parent_class.init(mode, json_data);

        if (mode.indexOf('view') > -1) {
          var isEmpty = function(tr) {
            var inputs = $('input', tr);
            for (var i = 0; i < inputs.length; i++) {
              if ($(inputs[i]).val()) {
                return false;
              }
            }
            return true;
          }

          $('#the_form tbody tr').each(function() {
            if (isEmpty(this)) {
              $(this).remove();
            }
          })
          return;
        }

        var nFixed = 2;

        $('#the_form input[name^=amount]').on('keyup change', function() {
          console.log('Key up change on Amount cell')
          var tr = $(this).closest('tr');
          var equiv = $('input[name^=equivalents]', tr);
          if (equiv.length != 1)
            throw ('Found the incorrect number of equiv inputs: ' + equiv.length)
          equiv = equiv.first();
          var moles1 = $('#the_form input[name=moles1_formula]');
          var fw = $('input[name^=fw]', tr);
          if ($(this).val() && fw.val() && moles1.val())
            equiv.val(($(this).val() / fw.val() / moles1.val()).toFixed(nFixed))
        });

        $('#the_form input[name^=fw]').on('keyup change', function() {
          console.log('Key up change on FW cell')
          var tr = $(this).closest('tr');
          var amount = $('input[name^=amount]', tr);
          var fw = $('input[name^=fw]', tr);
          var moles = $('input[name^=moles]', tr);
          var equiv = $('input[name^=equivalents]', tr);
          if (moles.val() && fw.val()) {
            amount.val((moles.val() * fw.val()).toFixed(nFixed))
          }
        });

        $('#the_form input[name^=fw]').on('change', function() {
          console.log('Key up change on FW cell')
          var tr = $(this).closest('tr');
          var amount = $('input[name^=amount]', tr);
          var equiv = $('input[name^=equivalents]', tr);
          if (!equiv.val()) {
            amount.change();
          }
        });
},

1 个答案:

答案 0 :(得分:0)

仅供参考,关于SO的一些问题会指定现有代码的结果,以及与预期结果有何不同,往往会获得更好的响应。 (有关更多信息,请参见this help page。)

在不知道这些细节的情况下,我仅向您展示我可能会使用的一种方法,目标是有条件地“启用”第一个数据行下方的行-注释应明确说明此内容的所有部分该脚本应该做。

(请注意,该页面需要从某处获取“ mode”的值,一种选择是在加载该页面之前,在浏览器的localStorage中设置该值。以下示例使用了该技术,但由于SO代码段已被沙箱化,并且无法访问localStorage,因此我已注释掉相关代码,并用“模式”的硬编码值替换了它。)

//
// When all inputs in the first data row have "truthy" values, enable the subsequent inputs
//

// Assume some other page set the "mode" and then directed the browser to our page
    //localStorage.setItem("mode", "edit"); 
    //window.location = "https://whateverdomain/whateverpage.com";
 
// Now on our page, get "mode" value, and define selectors.
    //let mode = localStorage.getItem("mode");
  let mode = "edit"; // Hard-coded for demo. Replace with above line.
  const initialRow = document.querySelector(".initialRow"),
        //(Note that querySelectorAll returns a [NodeList][2], similar to an array)
        initialRowInputs = document.querySelectorAll(".initialRow input"),
        otherRows = document.querySelectorAll(".otherRow"),
        otherRowInputs = document.querySelectorAll(".otherRow input");

// Disable inputs in other rows by default
  for(let input of otherRowInputs){
    //("input" is an arbitrary identifier for the current Node as we loop through the list)
    input.setAttribute("disabled", ""); 
  }
  
// From now on, listen for when any element in initialRowInputs gets "blurred" 
//   (ie, when it loses focus). Whenever this happens, call "enableInputs".
  for(let input of initialRowInputs){
    input.addEventListener("blur", enableInputs);
  }

// Our listener's "callback" function
  function enableInputs(event){
    // Create a flag to let the "enabling" be conditional
    let justKidding = true;
    // Set the flag based on mode
    if(mode == "edit"){ justKidding = false; }

    // Reset the flag if any element of initialRowInputs has a "falsey" value 
    //   (such as zero or an empty string)
    for(let input of initialRowInputs){
      if(input.value == false){ justKidding = true; }
    }
    // If the flag is still set to false, remove the "disabled" attribute from 
    //   all elements in otherRowInputs
    if(justKidding === false){
      for(let input of otherRowInputs){
        //(Note that "disabled" behaves as a [boolean attribute][2])
        input.removeAttribute("disabled");
      }
      console.log(" -- Inputs are enabled. --");
    }

    //(Properties of the triggering event are available in the listener's callback function,
    //  where "event" is an arbitrary name but must match the function's optional parameter.)
    const triggeringElement = event.target;
    const triggeringElementValue = triggeringElement.value;
    if(triggeringElementValue != false){
      console.log(`Input in first row: '${triggeringElementValue}'`);
    }
  }
<table>
  <tr>
    <th>Col1</th>
    <th>Col2</th>
  </tr>
  <tr class="initialRow">
    <td><input /></td>
    <td><input /></td>
  </tr>
  <tr class="otherRow">
    <td><input /></td>
    <td><input /></td>
  </tr>
  <tr class="otherRow">
    <td><input /></td>
    <td><input /></td>
  </tr>
</table>