You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS表单submit事件绑定失效及姓名正则优化问题求助

Hey there! Let's work through your two form development issues step by step:

Issue 1: Submit Event Not Triggering

The problem here is that you're trying to attach a submit event listener to the submit button itself—but the submit event belongs to the <form> element, not the button. When a user submits the form (either by clicking the button or pressing Enter), the event fires on the form, not the button.

Here's the fixed JavaScript code:

(function() { 
  "use strict"; 
  // Target the form element instead of the submit button
  document.getElementById('escribenos').addEventListener('submit', enviar); 

  function enviar(event) { 
    event.preventDefault(); // Prevents the default form submission page reload
    console.log("you submitted the form"); 
  } 
})();

This way, when the form is submitted, your function will fire as expected and log the message to the console.

Issue 2: Regex for Names with Middle Names

Your current regex [A-Za-z]+\s+[A-Za-z]+ only matches exactly two name parts. To support at least two parts (including middle names), we need to allow one or more additional "space + name" segments after the first name.

Use this updated regex pattern:

[A-Za-z]+(?:\s+[A-Za-z]+)+

Breakdown:

  • [A-Za-z]+: Matches the first name (one or more letters)
  • (?:\s+[A-Za-z]+)+: A non-capturing group (?:...) that matches a space followed by another name part. The + at the end means this group can repeat one or more times—ensuring there's at least one additional name part (so total of 2+ names).

Here's the updated HTML input line:

<input type="text" name="name" id="name" pattern="[A-Za-z]+(?:\s+[A-Za-z]+)+" required value=""/>

If you want the regex to be case-insensitive (so it accepts lowercase and uppercase letters without strict matching), you can add the (?i) flag at the start:

(?i)[A-Za-z]+(?:\s+[A-Za-z]+)+

内容的提问来源于stack exchange,提问作者roger rengifo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:46:16