在我的联系表单 7 中,我有两个单选按钮,它们根据用户所做的选择显示和隐藏联系表单中的字段。
当您单击“电话”单选按钮时,脚本(JS 而不是 jQuery)会确保隐藏电子邮件字段并且仅显示电话字段。当您单击电子邮件单选按钮时,将显示电子邮件字段并隐藏电话字段。该部分完全按照我希望的方式工作。
我遇到的问题是我无法弄清楚如何阻止 Contact Form 7 验证隐藏字段。例如,如果客户只想输入他们的电话号码而不是他们的电子邮件,插件由于电子邮件字段未填写,他们在尝试提交时仍会给出错误。
这是代码-
JS:
window.onload=radioCheck;
function radioCheck() {
if (document.getElementById('pcmPhone').checked) {
document.getElementById('client-phone').style.display = 'block';
document.getElementById('client-email').style.display = 'none';
document.getElementById('phone-input').setAttribute("aria-required", "true");
document.getElementById('email-input').setAttribute("aria-required", "false");
} else {
document.getElementById('client-phone').style.display = 'none';
document.getElementById('client-email').style.display = 'block';
document.getElementById('phone-input').setAttribute("aria-required", "false");
document.getElementById('email-input').setAttribute("aria-required", "true");
}
}
HTML(带有一些联系表 7 简码):
<div class="formFieldWrap">
Name:<br />
[text* client-name]
</div>
<div class="contactPref">
How would you like us to respond?
<br/>
<span class="wpcf7-form-control-wrap cpcm">
<span class="wpcf7-form-control wpcf7-radio" id="cpm">
<span class="wpcf7-list-item">
<input type="radio" id="pcmPhone" id="phone-input" name="cpcm" value="Phone Call" checked="checked" onclick="radioCheck();"/>
<span class="wpcf7-list-item-label">Phone Call</span>
</span>
<span class="wpcf7-list-item">
<input type="radio" id="pcmEmail" id="email-input" name="cpcm" value="E-mail" onclick="radioCheck();"/>
<span class="wpcf7-list-item-label">E-mail</span>
</span>
</span>
</span>
</div>
<div class="formFieldWrap" id="client-phone">
Phone:<br/>
[tel* client-phone]
</div>
<div class="formFieldWrap" id="client-email">
E-mail:<br />
[email* client-email]
</div>
<div class="formFieldWrap">
Message:<br />
[textarea client-message]
</div>
[submit id:contactSub "Send"]
我已尝试更改 aria-required 属性,如您在 javascript 中所见,但我遇到了两个问题 - 1) 我使用 JS 更改这些属性的方法不起作用。属性保持设置为真。 2) 当我在我的 firebug 中手动将它们更改为 false 时,它们仍然以某种方式验证。
所以我的问题是,隐藏时如何禁用表单域?
最佳答案
我也遇到了这个问题。我就是这样解决的。
我正在使用 WPCF7 的过滤器之一在验证之前更改发布的数据:
function alter_wpcf7_posted_data( $data ) {
if($_POST['cpcm'] == "E-mail") {
$_POST['tel'] = "Contact by email";
}
if($_POST['cpcm'] == "Phone Call") {
$_POST['tel'] = "Contact by phone";
}
return $data;
}
add_filter("wpcf7_posted_data", "alter_wpcf7_posted_data");
这样,WPCF7 的验证阶段会认为隐藏字段实际上已被填充。
注意:我没有具体测试过上面的代码,但是你应该明白了:)
编辑:上面的代码放在主题的 functions.php 文件中
关于javascript - 动态禁用 Contact Form 7 字段验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20925237/