首页 > 解决方案 > Select Field OnChange, Make Show/Hide, Shows Initially but Once Gone, Cant ReShow

问题描述

I have a select form field, which once the value of this field becomes "Location", the TR table row will change from display: none, to empty property. See below in head tag.

<script type="text/javascript">
     function disableit()
     {
         if (document.getElementById("typepicker").value === "Location") {
             document.getElementById("1-row").style.display = "";
          } else {
           document.getElementById("1-row").style.display = "none";
         }
     }
</script>

Then I have a select field, with disableit() being called once the option changes. Default option is "Location", and so the script runs, and the 1-row table row is being shown. Then, when choose different option, great, the table row gets display:none.

But problem, when I change option back to Location again, it not show the hidden TR...

<select class="alert-select" onChange="disableit();" id="typepicker" name="type">
    <option value="Location">Location</option>
    <option value="movement">First Movement</option>
</select>
<tr id="1-row">
    <td><label>At Location</label></td>
    <td>
        <select class="alert-select" name="Location" id="locationpicker">   
             //In here goes some dynamically generated <options> from php query, works fine                                                            
        </select>
    </td>
 </tr>

So to sum up, 1-row id table row is shown initially, because typepicker has option Location set by default as its first in the list, but when click a different option, it hides the row - great, but then click location again, and it does not show.

Any help much appreciated, thanks

标签: javascripthtml

解决方案


You need to sort out your mark-up (HTML):

  1. Your tr should be wrapped in a table tag. Without this, your table doesn't render properly.

  2. Remove the comment // In here goes some dynamically generated... or use a HTML comment instead: <!-- In here goes some dynamically generated... -->

Fixing these two issues seems to resolve your issue:

function disableit() {
  if (document.getElementById("typepicker").value === "Location") {
    document.getElementById("1-row").style.display = "table-row"; // change to display table-row
  } else {
    document.getElementById("1-row").style.display = "none";
  }
}
<select class="alert-select" onChange="disableit();" id="typepicker" name="type">
  <option value="Location">Location</option>
  <option value="movement">First Movement</option>
</select>

<table>
  <tr id="1-row">
    <td><label>At Location</label></td>
    <td>
      <select class="alert-select" name="Location" id="locationpicker">
        <option>France </option>
        <option>Australia </option>
        <option>UK </option>
        <option>Korea </option>
      </select>
    </td>
  </tr>
</table>


推荐阅读