使用JavaScript取消选中复选框时清除字段

时间:2018-07-04 13:09:18

标签: javascript html

我当前正在创建一个表单,其中包含几个物理地址字段和邮政地址字段,因此,如果用户填写了物理地址,并且邮政地址与物理用户相同,则需要选中要复制的框相同的信息,我已经成功完成了,但是我的目标是,当用户取消选中该复选框时,必须清除/删除复制到邮政地址中的信息。我哭了要复制一条else语句,并为Java重复同一段代码,然后将false代替true,但是它不起作用。

function FillTextbox(f) {
  if (f.checkbox2.checked == true) {
    f.Txtbox_PA.value = f.Txtbox_Address1.value;
    f.TxtPA2.value = f.Txt_Physical2.value;
    f.TxtPA3.value = f.Txt_Physical3.value;
    f.TxtPA4.value = f.Txt_Physical4.value;
    f.TxtPA5.value = f.Txt_Physical5.value;
  }

}
<form action="/action_page.php">

  <label>Physical Address:</label>
  <input type="text" name="Txtbox_Address1"><br>
  <input type="text" name="Txt_Physical2"><br>
  <input type="text" name="Txt_Physical3"><br>
  <input type="text" name="Txt_Physical4"><br>
  <input type="text" name="Txt_Physical5"><br>

  <em><b>(Check this box if Postal Address and Physical Address are the same.)</b></em>
  <input type="checkbox" name="checkbox2" onclick="FillTextbox(this.form)" aria-checked="undefined" />

  <label>Postal Address:</label>
  <input type="text" name="Txtbox_PA"><br>

  <input type="text" name="TxtPA2"><br>
  <input type="text" name="TxtPA3"><br>
  <input type="text" name="TxtPA4"><br>
  <input type="text" name="TxtPA5"><br>

</form>

1 个答案:

答案 0 :(得分:0)

三元组在这里效果很好

function FillTextbox(f) {
  var checked = f.checkbox2.checked;
  f.Txtbox_PA.value = checked ? f.Txtbox_Address1.value : "";
  f.TxtPA2.value    = checked ? f.Txt_Physical2.value   : "";
  f.TxtPA3.value    = checked ? f.Txt_Physical3.value   : "";
  f.TxtPA4.value    = checked ? f.Txt_Physical4.value   : "";
  f.TxtPA5.value    = checked ? f.Txt_Physical5.value   : "";
}
<form action="/action_page.php">

  <label>Physical Address:</label><br/>
  <input type="text" name="Txtbox_Address1"><br>
  <input type="text" name="Txt_Physical2"><br>
  <input type="text" name="Txt_Physical3"><br>
  <input type="text" name="Txt_Physical4"><br>
  <input type="text" name="Txt_Physical5"><br>

  <input type="checkbox" name="checkbox2" onclick="FillTextbox(this.form)" aria-checked="undefined" /><em><b>(Check this box if Postal Address and Physical Address are the same.)</b></em>
  <br/>

  <label>Postal Address:</label><br/>
  <input type="text" name="Txtbox_PA"><br>

  <input type="text" name="TxtPA2"><br>
  <input type="text" name="TxtPA3"><br>
  <input type="text" name="TxtPA4"><br>
  <input type="text" name="TxtPA5"><br>

</form>