Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  7] [ 1]  / answers: 1 / hits: 147073  / 12 Years ago, wed, july 18, 2012, 12:00:00

I have used this jquery validation plugin for the following form.



<script src=http://code.jquery.com/jquery-latest.js></script>
<script type=text/javascript src=http://jzaefferer.github.com/jquery-validation/jquery.validate.js></script>

<script>
$(document).ready(function(){
$(#commentForm).validate();
});

function addInput() {
var obj = document.getElementById(list).cloneNode(true);
document.getElementById('parent').appendChild(obj);
}
</script>

<form id=commentForm method=get action=>
<p id=parent>
<input id=list class=required />
</p>

<input class=submit type=submit value=Submit/>
<input type=button value=add onClick=addInput() />
</form>


When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs?
Thank you...


More From » jquery

 Answers
170

You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.



And here is my solution that I've tested and it works:



<script type=text/javascript>
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs

function addInput() {
$('#inputs').append($('<input class=comment name=name'+numberIncr+' />'));
numberIncr++;
}

$('form.commentForm').on('submit', function(event) {

// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules(add,
{
required: true
})
});

// prevent default submit action
event.preventDefault();

// test if form is valid
if($('form.commentForm').validate().form()) {
console.log(validates);
} else {
console.log(does not validate);
}
})

// set handler for addInput button click
$(#addInput).on('click', addInput);

// initialize the validator
$('form.commentForm').validate();

});


</script>


And the html form part:



<form class=commentForm method=get action=>
<div>

<p id=inputs>
<input class=comment name=name0 />
</p>

<input class=submit type=submit value=Submit />
<input type=button value=add id=addInput />

</div>
</form>


Good luck! Please approve answer if it suits you!


[#84185] Tuesday, July 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jovanymarshalld

Total Points: 676
Total Questions: 94
Total Answers: 81

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;