gpt4 book ai didi

用于检查字段是否为空的 Javascript 函数

转载 作者:太空宇宙 更新时间:2023-11-04 08:19:04 25 4
gpt4 key购买 nike

以下函数可用于检查用户是否在给定字段中输入了任何内容。空白字段可以表示两种值。零长度字符串或 NULL 值。

function required()  
{
var empt = document.forms["form"]["text"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
li {list-style-type: none;  
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}
<!doctype html>  
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body>
<div class="mail">
<h2>Input your Name and Submit</h2>
<form name="form1" action="#" onsubmit="required()">
<ul>
<li><input type='text' name ='text1'/></li>
<li class="rq">*Required Field</li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</div>
<script src="non-empty.js"></script>
</body>
</html>

我正在尝试这段代码,但无法运行脚本。如果有帮助,我也在使用 jquery.js

我该如何解决这个问题?

最佳答案

您的表单和文本字段的名称在 javascript 中是错误的。我已在以下代码段中更正此问题。

只有行“var empt = document.forms["form1"]["text1"].value;”改变了。

function required()  
{
var empt = document.forms["form1"]["text1"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
li {list-style-type: none;  
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}
<!doctype html>  
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body>
<div class="mail">
<h2>Input your Name and Submit</h2>
<form name="form1" action="#" onsubmit="required()">
<ul>
<li><input type='text' name ='text1'/></li>
<li class="rq">*Required Field</li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</div>
<script src="non-empty.js"></script>
</body>
</html>

关于用于检查字段是否为空的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674752/

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