gpt4 book ai didi

javascript - 更改表单名称的表单验证

转载 作者:行者123 更新时间:2023-11-28 02:37:31 26 4
gpt4 key购买 nike

我有一系列使用 php 动态创建的表单。

表单名称是使用 php $formcount 变量创建的,并使用 while 循环递增。因此,对于创建的多个表单,表单名称将为:更新1更新2update3等等。

我在每个表单中都有一个需要验证的下拉菜单。我无法成功使用 JavaScript 来单独验证每个表单,因为表单的名称每次都会发生变化。

$formcount=0;
while($info=mysql_fetch_array($agent_q))
{
......
echo('
<form name="update'.$formcount.'" method="post" onsubmit="return CheckUpdate(this);">
<select name="login_time" id="login_time">
<option value="none">Select Login</option>
<option value="00:30">00:30</option>
<option value="02:30">02:30</option>
<option value="03:30">03:30</option>
<option value="04:30">04:30</option>
<option value="06:30">06:30</option>
<option value="09:30">09:30</option>
<option value="12:30">12:30</option>
<option value="13:30">13:30</option>
<option value="16:30">16:30</option>
<option value="17:30">17:30</option>
<option value="18:30">18:30</option>
<option value="19:30">19:30</option>
<option value="20:30">20:30</option>
<option value="21:30">21:30</option>
<option value="22:30">22:30</option>
</select></form>');
.....
}

我的JS是

function CheckUpdate(){
if(document.????==0){
alert("Select Login Time!\r\n");
return false;
}
else
return true;
}

不知道用什么来代替???。我确信这相当简单......任何帮助都非常感谢。谢谢!

最佳答案

有几种方法可以实现这一点。可能最简单的(无需修改现有的 PHP)是使用 form.elements 收藏。在您的情况下,<select>将是elements[0]

// The form node is passed in the function call as (this)
function CheckUpdate(node){
// The first form element in the form node passed to the function is the <select>
// Test that a value other than the default is selected...
if (node.elements[0].value == 'none'){
alert("Select Login Time!\r\n");
return false;
}
else return true;
}

还有其他方法可以解决这个问题。例如,如果始终只有一个 <select>里面<form> ,但它不一定位于第一个位置 [0] ,您可以使用getElementsByTagName()将其检索为当前 <form> 的子项

function CheckUpdate(node){
var selNodes = node.getElementsByTagName('select');
// Check the value of the first <select> child of the <form> (which was passed as node)
if (selNodes[0].value == 'none'){
alert("Select Login Time!\r\n");
return false;
}
else return true;
}

注意:在 PHP 循环中,您复制 <select> id 属性。这是不允许的 - id 属性应该是唯一的。您可以附加您的$formcount .

echo '
<form name="update'.$formcount.'" method="post" onsubmit="return CheckUpdate(this);">
<select name="login_time" id="login_time' . $formcount . '">
...;

关于javascript - 更改表单名称的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13238774/

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