Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

javascript - Creating HTML Dynamic FORM using JS

I'm trying to create a dynamic form using JS and PHP, I've done the PHP part, where the user selects how many rows he wants and the program generate that number of rows. The JS part is to display a HTML select box only if a checkbox is checked. I done that using the following function:

var checkBox = document.getElementById("box");
function repeatedCheck(){
  if(checkBox.checked==true){
  document.getElementById('sel').innerHTML="<select name='sel'>
  <option value='1'>1</option>
  <option value='2'>2</option>
  .
  .
  //more options ..
  </select>";}
  else{
    document.getElementById('sel').innerHTML="";
  }
}

and this is the HTML part which generated by PHP program:

<table>
<?php
    for($i=1;$i<=$numOfRows;$i++){
           echo "<tr>";
           echo "<td><input type='checkbox' id='box' name='repeated' onclick='repeatedCheck()'></td>";
           echo "<td id='sel'></td>";
           echo "</tr>";
       }
?>
</table>

The problem is, nothing shows up when the checkbox is checked.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try the following.

You are missing the input event, so your function does not run when user changes the checkbox state.

Additionally, I recommend you to have your select input already written in HTML instead of using innerHTML. Or at least create the element manually with document.createElement() if you need to change options dynamically.

Please let me know if you have any doubt.

const checkboxes = document.getElementsByClassName('checkbox');

function onChangeHandler(e){
  if (e.target.checked === true) {
    e.target.nextElementSibling.style.display = null;
  } else {
    e.target.nextElementSibling.style.display = 'none';
  }
}

for (let i = 0; i < checkboxes.length; i++) {
  checkboxes[i].addEventListener('change', onChangeHandler);
}
<form>
  <div>
    <input class='checkbox' type='checkbox'></checkbox>
    <select name='select' style='display: none;'>
      <option value='1'>1</option>
      <option value='2'>2</option>
    </select>
  </div>
  
  <div>
    <input class='checkbox' type='checkbox'></checkbox>
    <select name='select' style='display: none;'>
      <option value='1'>1</option>
      <option value='2'>2</option>
    </select>
  </div>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...