【问题标题】:Is it possible to make a textbox required only after display has been changed to "Block"是否可以仅在显示更改为“阻止”后才需要文本框
【发布时间】:2020-10-30 10:27:04
【问题描述】:

我正在尝试在 WordPress 联系表 7 中制作报价请求联系表。现在我的网站中有多个不同的部门可以提出报价请求。我希望他们都指向同一个网站,以尽量减少工作等。

现在人们可以在 5 个不同的复选框中选择他们想要报价的部门。对于每个部门,我需要提出 2 个具体问题,以使自己更容易进行报价,但这些问题仅应在选中该复选框时显示。我已经这样做了:

function myFunction() {
  // Get the checkbox
  var checkBox = document.getElementById("Propulsion and Stabilization");
  // Get the output text
  var text = document.getElementById("text");

  // If the checkbox is checked, display the output text
  if (checkBox.checked == true){
    text.style.display = "block";
    } else {
    text.style.display = "none";
  }
}

这就是我在联系表格中使用的内容,在勾选方框时会显示“船长”和一个文本框。

<p id="text" style="display:none"><label> Ship Length 
[text text-234]</p> </label>

选中该框后,“文本”(问题)将显示得非常好。 现在我的问题是如何让人们填写“必填”的问题?我尝试在 document.getElementById("text"); 之后正常添加 required但由于某种原因,我无法让它工作。有什么想法吗?

谢谢! Before Ticking box Ticked box result

【问题讨论】:

  • 可以将元素的required属性设置为真/假(text.required = true
  • 在将显示设置为block 后的下一行,只需添加另一行text.setAttribute('required', 'required'); 并且每当您将显示设置为none 时,只需删除required 属性。
  • 我想这就是你要找的东西。类似的问题已经回答了stackoverflow.com/questions/18770369/…
  • // 如果复选框被选中,则显示输出文本 if (checkBox.checked == true){ text.style.display = "block"; text.required = true} else { text.style.display = "none"; text.required = false} } 如果我理解正确,这应该可以工作?
  • @maswerdna 很遗憾无法弄清楚。有机会再看看吗?谢谢!

标签: javascript html wordpress forms


【解决方案1】:

遗憾的是,我还没有设法让它工作。 我已经尝试了多种变体:

function myFunction() {
  // Get the checkbox
  var checkBox = document.getElementById("Propulsion and Stabilization");
  // Get the output text
  var text = document.getElementById("text"); 

  // If the checkbox is checked, display the output text
  if (checkBox.checked == true){
    text.style.display = "block";
    text.setAttribute("required", "");}
    else {
    text.style.display = "none";
    element.removeAttribute("required");}
}

但这不起作用。

【讨论】:

  • 好吧,我想我刚刚理解了你的问题。您需要注意一些事项: 1. required attribute 仅适用于 form 元素,例如 inputcheckboxradio 等。它不能在 span、@987654328 上运行@ 等 (2)。该元素必须在 form 元素内才能按要求工作。当您在非表单元素上设置属性时,浏览器silently 会忽略它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 2014-09-11
  • 2012-10-21
  • 1970-01-01
相关资源
最近更新 更多