JavaScript代码不起作用
我正在尝试使用JavaScript检测文本字段中的空格,因此每当文本字段中有空格时,都会弹出一个警报,但此代码不起作用,它应该在两个文本字段上都起作用JavaScript代码不起作用,javascript,html,Javascript,Html,我正在尝试使用JavaScript检测文本字段中的空格,因此每当文本字段中有空格时,都会弹出一个警报,但此代码不起作用,它应该在两个文本字段上都起作用 <!DOCTYPE html> <html> <script type="text/javascript"> function detectSpace() { $returnValue = preg_match('/[^a-z^A-Z^0-9]/', $str,
<!DOCTYPE html>
<html>
<script type="text/javascript">
function detectSpace() {
$returnValue = preg_match('/[^a-z^A-Z^0-9]/', $str, $matches);
if ($returnValue==1)
{
alert("spaces & symbols are not allowed");
}
}
</script>
<body onload="detectSpace()">
<form action="demo_form.asp">
First name: <input type="text" name="FirstName" value=""><br>
Last name: <input type="text" name="LastName" value=""><br>
<input type="submit" value="Submit">
</form>
<p>Click the "Submit" button and the form-data will be sent to a page on the server called "demo_form.asp".</p>
</body>
</html>
函数detectSpace(){
$returnValue=preg_match('/[^a-z^a-z^0-9]/',$str,$matches);
如果($returnValue==1)
{
警告(“不允许使用空格和符号”);
}
}
名字:
姓氏:
单击“提交”按钮,表单数据将发送到服务器上名为“demo_form.asp”的页面
preg_match
是一个PHP函数,而不是JavaScript函数——由于后端代码是ASP!PHP和JavaScript是不同的语言。要匹配JavaScript中的字符串,您需要将代码更改为:
function detectSpace(str) {
var expression = new RegExp(/\s/);
var returnValue = expression.test(str);
if (returnValue === true)
alert("spaces & symbols are not allowed");
}
这样,您需要在detectSpace
函数中将要测试的值作为参数传入:
detectSpace("foo"); // No alert fired
detectSpace("foo bar"); // Alert fired
请注意,我还将正则表达式更改为
/\s/
-这与空格匹配,如果找到任何空格,将返回true
。JavaScript中没有preg\u match
函数。什么是“$str”和“$matches”,您在哪里定义这些变量?$str
也未定义。您运行的函数不知道与您的RegExp匹配什么。。。您似乎将PHP和JS混为一谈。preg_match在javascript中不可用。请参阅:在firebug中获得以下错误:ReferenceError:preg_匹配不匹配defined@HassanChaudhry请提供更多细节。什么不起作用?下面是一个JSFIDLE演示,演示了如何在文本字段中使用它?因为在演示中没有HTML,所以我想让它检测文本字段上的空格@HassanChaudhry,您需要循环使用输入[type=“text”]
表单中的元素并通过上面我为您编写的detectSpace
函数检查它们的值,方法是在表单的submit
事件上添加事件侦听器。