I have a form which has a "phone" field and a button of "add another phone number".
<div class="form-group form-inline phone">
<label class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="phonetype1" placeholder="Type of Phone">
<input type="text" class="form-control" id="number1" placeholder="Write here your phone number">
</div>
</div>
<span id="newPhone"> Add a phone number</span>
When I click this button, another group of fields shows to fill with another phone number:
$("#newPhone").on('click',function(){
var numItems = $('.phone').length +1;
var newPhone= '<div class="form-group form-inline phone">';
newPhone+= '<label class="col-sm-2 control-label"></label>';
newPhone+= '<div class="col-sm-10">';
newPhone+= '<input type="text" class="form-control" id="phonetype'+numItems+'" placeholder="Type of Phone">';
newPhone+= '<input type="text" class="form-control" id="number'+numItems+'"" placeholder="Write here your phone number">';
newPhone+= '</div> </div>';
$(this).before(newPhone);
});
But then I want to access to these new fields in order to validate their data:
$(function()
{
$("input").on('blur',function(){
var formElementId = $(this).attr("id");
validateField(formElementId); //This function works, for sure
});
});
This function is not executed for the new fields. I think this is because the DOM tree is not updated so my jQuery function does not know about these new input fields.
How can I access them even if they are not in the DOM tree? if is not possible, or if it's better, how can I insert my fields into the DOM tree?
Thank you all :)
EDIT:
5 more minutes of research and I've nailed the solution
I misused on(), here's how to delegate correctly the blur event
$("form").on('blur','input',function(){
var formElementId = $(this).attr("id");
validateField(formElementId); //This function works, for sure
});