如何从这个javascript验证动态生成的字段?

时间:2013-08-31 12:28:41

标签: javascript

currentg1 = 1; // This is input files added by default.
maxg1 = 5;
ming1 = 1;
contor = 3;
contor1 = 4;
valuek = 2;
function g1_app_child(){
if(currentg1<maxg1)
{
    var div = document.createElement("div");
    div.id = 'divfiles'+currentg1;
    /*div.style.width = "100px";
    div.style.height = "100px";
    div.style.background = "red";
    div.style.color = "white";*/
    div.innerHTML = '<a href="javascript:void();" onclick="g1_delchild()">Remove websites</a><br><table><tr><td><input type="hidden" name="on'+contor+'" value="Keywords" class="special">Keywords: </td></tr><tr><td><input type="text" name="os'+contor+'" maxlength="200" id="keywords" class="special">ex: seo services</td></tr><tr><td><input type="hidden" name="on'+contor1+'" value="Website" class="special">Website: </td></tr><tr><td><input type="text" name="os'+contor1+'" maxlength="200" id="website" class="special">ex: seoadsem.com</td></tr><input type="hidden" name="quantity" value="'+valuek+'"></table>';
    document.getElementById('outer_div').appendChild(div);
currentg1++;
valuek++;
    if (contor%2) {
        contor1++ == contor++ + 1;
    }
    else {
        contor++;
    }
contor++;
contor1++;
    return false;
}
else
{
    alert('Maximum '+maxg1+' 5 websites are allowed');
    return false;
}
}

function g1_delchild()
{
if(currentg1>ming1)
{
    cnt = currentg1-1;
    element = document.getElementById('divfiles'+cnt);
    element.parentNode.removeChild(element);
    currentg1--;
    return false;
}
else
{
    alert('Minimum '+ming1+' Website Allowed');
    return false;
}
}

function validateForm() {
"use strict";
/*global document: false */
/*jshint sub:true*/
/*jslint browser: true, devel: true */
var w = document.forms.myPayPal.os0.value;
var x = document.getElementById('keywords').value;
var y = document.getElementById('website').value
if (x == null || x == "") {
    alert("Please input keywords");
    document.getElementById('keywords').focus() 
    return false;
}
if (y == null || y == "") {
    alert("Please input website");
    document.getElementById('website').focus() 
    return false;
}
if (w === "0") {
    alert("You must agree to the terms of service");
    return false;
}

}

当我尝试它时,它只验证初始字段。 当它开始验证它时,当我点击更多字段并单击提交时不会通过。这是测试页面:http://www.seoadsem.com/full-SEO-report-for-your-website-test.html

1 个答案:

答案 0 :(得分:2)

当您使用getElementById(它将选择第一个)时,页面上只能有一个具有相同ID的元素,您不应该使用多个(使用类代替)。但是,如果使用:

,您仍然可以验证当前脚本
[].slice.call(document.querySelectorAll('#keywords')).forEach(function(keyword) {
    // validate keyword here
});

它将选择id = keywords

的所有元素