javascript - access to appended/prepended elements -


i have form has "phone" field , button of "add 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 phone number">     </div> </div> <span id="newphone"> add phone number</span> 

when click button, group of fields shows fill 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 phone number">';     newphone+= '</div> </div>';     $(this).before(newphone); }); 

but want access these new fields in order validate data:

$(function() {     $("input").on('blur',function(){         var formelementid = $(this).attr("id");         validatefield(formelementid); //this function works, sure     }); }); 

this function not executed new fields. think because dom tree not updated jquery function not know these new input fields.

how can access them if not in dom tree? if not possible, or if it's better, how can insert fields dom tree?

thank :)

edit:

5 more minutes of research , i've nailed solution

i misused on(), here's how delegate correctly blur event

$("form").on('blur','input',function(){     var formelementid = $(this).attr("id");     validatefield(formelementid); //this function works, sure }); 

event delegation key, see on() documentation method

plus ..

since blur event not bubble up, try "focusout event"

doc:

the focusout event sent element when it, or element inside of it, loses focus. distinct blur event in supports detecting loss of focus on descendant elements (in other words, supports event bubbling).


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -