【发布时间】:2017-10-13 03:23:49
【问题描述】:
我正在处理的网页上的表单可以在桌面上完美运行,但无法在移动设备(iPad 和 iPhone)上运行。当您点击“提交消息”按钮时,没有任何反应。确认消息没有出现,我也没有收到电子邮件(使用后端的 nodemailer 向我发送电子邮件)。我尝试了以下方法:
- 在桌面和移动设备上的表单上使用相同的“提交”事件侦听器
- 在按钮上为移动设备的“touchend”事件添加事件侦听器
- 在 HTMLFormElement 对象中使用 onsubmit 属性而不是使用事件监听器
这是 HTML:
<section id="contactContainer">
<section id="form"><a id="contact"></a>
<h2>Contact Me</h2>
<form action="/formSubmission" method="post">
<label for="reason">Reason for reaching out:</label>
<select name="reason">
<option value="Marketing">Marketing</option>
<option value="Web Development">Web Development</option>
<option value="other">Other</option>
</select><br>
<div>
<input type="text" name="firstName" placeholder="First Name" class="name" required>
<input type="text" name="lastName" placeholder="Last Name" class="name" required>
</div>
<input type="text" name="company" placeholder="Company" required><br>
<input type="text" name="email" placeholder="Email Address" required><br>
<textarea name="message" placeholder="Let me know what you're looking for."></textarea>
<input type="submit" value="Send Message" name="submit">
</form>
</section>
<section id="confirmation">
<h2>Thanks for sending! I'll be in touch shortly.</h2>
</section>
</section>
还有原版 JS:
var form = document.querySelector('form'),
button = document.querySelector('form input[name="submit"]'),
confirmation = document.querySelector('#confirmation h2'),
formSection = document.querySelector('#form');
form.addEventListener('submit', submit);
button.addEventListener('touchend', submit);
function sortFormData(form) {
var parsedForm = {},
elements = [...form.elements];
elements.forEach(element => {
if(element.name) {
parsedForm[element.name] = element.value;
}
})
return JSON.stringify(parsedForm);
}
//Form confirmation
HTMLElement.prototype.makeTransparent = function() {
this.style.opacity = 0;
this.style['z-index'] = 0;
}
HTMLElement.prototype.appear = function() {
this.style['z-index'] = 1;
this.style['font-size'] = '0px';
this.style.opacity = 1;
if(this.style['font-size'] === '0px') {
console.log('Animation start.');
}
this.classList.add('submitted');
}
//Helper function
function submit(e) {
e.preventDefault();
var formData = sortFormData(form);
var request = new XMLHttpRequest()
request.open('POST', './formSubmission', true);
request.setRequestHeader('Content-type', 'application/json');
request.send(formData);
formSection.makeTransparent();
confirmation.appear();
}
感谢任何帮助!
【问题讨论】:
标签: javascript html forms