如何使用 JavaScript 验证动态生成的文本字段


how to validate the dynamically generated text field using javascript

>我添加了使用具有动态名称的 PHP 动态生成的 5 个文本字段。如何使用 JavaScript 验证这些字段。这是小示例代码,但如果您帮助我使用以下代码进行此类验证,我的实际代码是不同的,我可以在那里做到这一点。 帮帮我。。。。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function validate()
{
//help me to write validation code here.
}
</script>
</head>
<body>
<form method="post" action="##" name="test" onsubmit="return validate()">
<?php
$i=0;
while($i<5)
{
echo "<input type='text' name='count$i'>"
$i++;
}
echo "<input type='submit' value='ok'>";
?>
</form>
</body>
</html>

将类添加到元素。将类添加到元素的目的是仅捕获那些已动态添加并想要验证的元素

while($i<5)
{
    echo "<input class='validate-it' type='text' name='count$i'>"
    $i++;
}

在 JS 中

<script>
function validate()
{
    var elems = document.getElementsByClassName('validate-it');
    for(var i=0; i<elems.length; i++) { 
        // Validate here
        // Code here depends on the type of validation you wants
    }
}
</script>

如果您描述要执行的验证类型,我肯定会编辑答案。希望这有帮助...

我直言,类更适合为CSS格式目的标记元素,而不是为脚本页面中的元素提供功能目标。

我建议为表单分配一个 ID,这样您就可以使用 javascript 引用它,使用 getElementById 函数选择它,然后浏览其元素并为每个元素执行您的验证函数,例如 validateField()。大致像这样

function validateField(fieldToValidate) {
    //Here you can perform your validation against fieldToValidate.value (for text inputs)
}

var frm = document.getElementById("myForm");
for (var i=0; frm.elements[i]; i++)
{//Cycle through all input tags, of text type, inside the form
    if (
       frm.elements[i].tagName=="INPUT" 
       &&
       frm.elements[i].getAttribute("type")=="text")
       )
    {
        validateField(frm.elements[i]);
    }
}

此外,如果您知道动态生成的元素的名称遵循给定的命名约定,例如在您的示例中(countX,X 是一个数字),并且您只想验证动态生成的输入字段,因为它们是文本输入字段,您可以只检查 thoose; 最好是将特定 ID 而不是名称分配给字段, 以确保您没有使用相同的名称并验证您不应该使用的内容。

PHP端

<form method="post" action="##" id="myForm" name="test" onsubmit="return validate()">
<?php
$i=0;
while($i<5)
{
echo "<input type='text' id='txtField$i'>"
$i++;
}
?>

JS端

function validateField(fieldToValidate) {
    //Here you can perform your validation against fieldToValidate.value (for text inputs)
}

var frm = document.getElementById("myForm");
var currentField;
for (var i=0; currentField = document.getElementById("txtField"+i); i++)
{//Cycle through all txtField* starting IDs elements
    validateField(currentField);
}

您没有命名详细的验证类型(范围内的数字?具有特殊内容的字符串?等),因此这是验证框架的常用方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <script type="text/javascript">
        function validate()
        {
            var allInputsOk = true;
            var inputs = document.getElementsByTagName("input");
            for (var inpx in inputs) {
                if (inpx.substring(0, 5) == "count") {
                    // it's one of the inputs named "count..."
                    var inpIdx = inpx.substr(5);
                    var inpObj = document.getElementsByName(inpx)[0];
                    var inpVal = inpObj.value;
                    allInputsOk &= validateSingleInput(inpIdx, inpVal);
                    if(!allInputsOk) break;
                }
            }
            return allInputsOk;
        }
        /*
         * Tests the value of the input named "countX"
         * @return true if "value" is valid for input "count<index>", false else
         */
        function validateSingleInput(index, value) {
            var inputValueNumber = Number(value); // in case to test for numeric inputs
            var inputValueString = String(value); // in case to test for string inputs
            // your validation test here ... return true or false
            return true; // dummy 
        }
    </script>
</head>
<body>
    <form method="post" action="#" name="test" onsubmit="return validate()">
        <?php
        $i=0;
        while($i<5)
        {
        echo "<input type='text' name='count$i'>";
        $i++;
        }
        echo "<input type='submit' value='ok'>";
        ?>
    </form>
</body>
</html>