如何验证按钮单击时创建的字段

时间:2016-10-20 06:29:37

标签: javascript php jquery html css

我的概念是在按钮上单击“+”创建最多20个字段,如果点击“+”按钮,则可以添加新字段,即成功完成..但现在我的问题是对字段进行验证这是在“+”按钮上创建的。

我有验证代码,但它只适用于一个字段..任何人都可以帮助我处理所有领域。  这是我的示例代码..

<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script src="js/jQuery - v1.11.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('#myform').validate({ 
    rules: {
        userid: {
            required: true,

        },
    },
    submitHandler: function (form) { // for demo
        alert('valid form submitted'); // for demo
        return false; // for demo
    }
});

});
</script>
<script>
var field = 1;
function add_fields() 
{
field++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="label">Field '+ field +':</div><input            type="text" name="userid " id="userid' + field +'" maxlength="50"    placeholder="User ID"  class="userid"/></div>';
objTo.appendChild(divtest)
}
</script>
</head>
<body>
<form id="myform">
<input type="button" id="more_fields" onclick="add_fields();" value="+" />
<div id="room_fileds">    
<div class="label">Field 1:</div>  
<input type="text" name="userid" id="userid" maxlength="50" placeholder="User ID"  class="userid"/><br>
</div>
<input type="submit" />
</form>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

看起来验证不适用于动态添加的输入。

为此,您需要通过

为新创建的输入添加规则
$('input').rules('add', 'required')

答案 1 :(得分:2)

在添加字段方法中,您必须重新验证表单并添加新规则。

<script>
var field = 1;
function add_fields() 
{
    field++;
    var objTo = document.getElementById('room_fileds')
    var divtest = document.createElement("div");
    divtest.innerHTML = '<div class="label">Field '+ field +':</div>    <input type="text" name="userid " id="userid' + field +'" maxlength="50"    placeholder="User ID"  class="userid"/></div>';
    objTo.appendChild(divtest);
    $('#myform').validate();
    $("input#userid" + field).rules("add", "required");
}
</script>

查看documentation

答案 2 :(得分:1)

计算你附加div添加更多按钮点击:

function add_fields()  {
  var apendedDivCount = 1;
  apendedDivCount = document.querySelectorAll('.userid').length; // Count of appended div with class "userid"
  if (apendedDivCount < 21) { // Condition to allow maximum 20 userid class div
    field++;
    var objTo = document.getElementById('room_fileds')
    var divtest = document.createElement("div");
    divtest.innerHTML = '<div class="label">Field '+ field +':</div>
    <input type="text" name="userid" id="userid' + field +'" maxlength="50" placeholder="User ID" class="userid"/></div>';
objTo.appendChild(divtest);
  } else {
      alert ("You can't add more than 20");
 }
}