gpt4 book ai didi

点击时的 JavaScript

转载 作者:行者123 更新时间:2023-11-29 21:38:36 25 4
gpt4 key购买 nike

我正在尝试对这个电话号码进行地面验证,但我在使用 onclick 方法时遇到问题,为什么它不起作用?

function validatePhone(){
var phone = document.getElementById("phone1").value;
if(phone.length === 0) {
alert("phone number is required.");
}
}
<form>
<p>Please enter your phone number below:</p>
<input id="phone1" placeholder="(000)000-0000" />
<input type="submit" value="send message" onclick="validatePhone()" />
</form>

最佳答案

将输入类型更改为 button,因为如果类型为 submit validatePhone() 将永远无法到达:

function validatePhone()
{
var phone = document.getElementById("phone1").value;

if(phone.length === 0) {
document.getElementById("result").textContent ="phone number is required.";
}
}
<form>
<p>Please enter your phone number below:</p>
<input id="phone1" placeholder="(000)000-0000" />
<input type="button" value="send message" onclick="validatePhone()" />
</form>
<span id='result'></span>

或者你可以使用onsubmit :

function validatePhone(e)
{
e.preventDefault();

var phone = document.getElementById("phone1").value;

if(phone.length === 0) {
document.getElementById("result").textContent ="phone number is required.";

return false;
}
}
<form onsubmit="validatePhone()"
<p>Please enter your phone number below:</p>
<input id="phone1" placeholder="(000)000-0000" />
<input type="submit" value="send message" />
</form>
<span id='result'></span>

关于点击时的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34010173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com