javascript - How do I unbind events on elements that are not the last -
i'm trying make form input appends empty input field end of series, if value of previous field true. i'v gotten pretty far i'm having trouble re-binding last element.
function removeempty(){ $('p:last').remove() } function init(){ $('p:last input').focus(function(event){ $(event.target).closest('p').append("<p class=''><label>middlename: </label><input></input></p>") init() }) $('p:last input').blur(function(event){ console.log($(event.target).val()) if(!$(event.target).val()){ removeempty() } }) } init()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <p class="first"> <label>middlename: </label><input></input> </p>
you use event delegation
instead.
instead of using this:
$('p:last input').focus(...); $('p:last input').blur(...);
you use this:
$('body').on("focus","p:last input", function() { ... }); $('body').on("blur","p:last input", function() { ... });
i've updated code:
function removeempty(){ $('p:last').remove() } function init(){ $("body").on('focus','p:last',function(event){ var target = $(event.target); target.closest('p').append("<p class=''><label>middlename: </label><input></input></p>"); target.one("blur",function() { if(!target.val()) { removeempty(); } }); }) } init()
see http://api.jquery.com/on/ , http://api.jquery.com/one/
i guess fiddle want!
Comments
Post a Comment