You have some issues with your code:
1) When you use the .rules('add')
method on a selector of multiple elements, you must nest it inside a jQuery .each()
or it won't be applied to all the matching elements.
$('.newinput').each(function() {
$(this).rules('add', {
'required': true
});
});
However, you can probably skip .rules()
entirely. See item #2 below.
2) You can totally forget about item #1 above since you're only trying to make these new fields required
. Simply add a required="required"
attribute (which I see you've already done) when you create them and you will not need to worry about the .rules('add')
method at all. Alternatively, you could use class="required"
instead, which is the method I chose for the demo below.
3) This is why nothing was working: Your newly added elements must also contain unique names
. It's a requirement of the plugin that all form inputs need a name
atribute. It's how the plugin keeps track of the elements, so they all need to be unique. However, as per your code, they do not. Your newly created elements all have the same exact name
assigned to them as your existing elements. Fix it by adding a counter and incrementing it to the name
each time you append to the form.
$(function () {
validar();
cvFields();
});
function validar() {
$(".validate").validate({
....
});
}
function cvFields() {
var count = 0;
$('#addcvfields').click(function (e) {
e.preventDefault();
count++;
var total = $()
var campos = '' +
....
'<input name="profesorcv_titulo[' + count + ']" type="text" class="form-control required" placeholder="Titulo de Estudio o Experiencia">' +
....
'<select name="profesorcv_tipo[' + count + ']" class="form-control required">' +
....
'<textarea rows="3" name="profesorcv_descripcion[' + count + ']" class="form-control" id="profesorcv_descripcion" placeholder="Describe Brevemente"></textarea>' +
....;
$('#cvfields').append(campos);
});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…