如何使用Javascript根据内容检查和更改表单的提交值?
我想在提交表单时根据其内容更改输入字段的值。
目前我有这个,并期望我距离我实际需要的东西还有很长的路要走,似乎无法找到我想要的信息来使其全部协同工作。
任何帮助表示赞赏。
<script type="text/javascript">
function vet()
{
if(this.abc.value.indexOf("CW-") >= 0)
{
return true;
}
else
{
this.abc.value = 'CW-' + this.abc.value; return true;
}
}
</script>
<form name="simple1" method="get" onsubmit="vet()" action="simple.php">
<input class="saip1" name="abc" type="text" value="Input Value" onfocus="this.value='';"/>
基本上我想检查用户是否在其值的开头包含“CW-”(或者实际上是 CW- cW- Cw- 的任何大小写变体)。如果他们只是按原样返回值。如果没有,我想添加 CW-。
经过一番阅读后,我尝试了indexOf方法,但我并不真正理解javascript,并且确信我做错了什么。
I would like to change the value of an input field when the form is submitted depending on it's content.
Currently I have this and expect I am a long way from what I actually need, can't seem to find the info I am after to make it all work together.
Any help appreciated.
<script type="text/javascript">
function vet()
{
if(this.abc.value.indexOf("CW-") >= 0)
{
return true;
}
else
{
this.abc.value = 'CW-' + this.abc.value; return true;
}
}
</script>
<form name="simple1" method="get" onsubmit="vet()" action="simple.php">
<input class="saip1" name="abc" type="text" value="Input Value" onfocus="this.value='';"/>
Basically I want to check that the user has included "CW-" (or indeed any case variant of that cw- cW- Cw-) at the beginning of their value. If they have just return the value as it is. If not I would like to add CW-.
After some reading I tried the indexOf approach but I don't really understand javascript and am sure I have done something wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的方法很好,但你让它变得有点复杂。
另外,通过 JavaScript 而不是通过 HTML 使用
onsubmit
等也是一个很好的做法。您也可以对onfocus
执行此操作。http://jsfiddle.net/PTspF/
HTML:
JavaScript:
您可以检查
indexOf
是否为0
,因为您希望“CW-”出现在字符串的开头。toUpperCase()
使cw-
CW-
以便变体也被发现是正确的。Your approach is fine but you were making it a little complicated.
Also, it's good practice to use
onsubmit
etc. through JavaScript instead of through HTML. You could also do this foronfocus
.http://jsfiddle.net/PTspF/
HTML:
JavaScript:
You could check for an
indexOf
of0
as you wish "CW-" to appear at the beginning of the string. ThetoUpperCase()
makescw-
CW-
so that variations also are found correct.