sometimes, we want to add more than one items(no limit, can be as more dynamically) but not in a text box, usually we use list box for that. User type one, click a button, it goes to the list, then we save.
However, for a better user experience we can use dynamic text box where a new dynamic text box will be created as soon as someone is typing on the current one. When, user finishes putting data, they can also delete as many as they want also. Here is a simple jquery implementation of this task:
we first, need a div as container ,a text box for putting data and an anchor for close button.
<div class="any_classname">
<input type="text" name="txtAuthor" class="author" size="23">
<a href="#">X</a>
</div>
to make our code a reusable plugin, write like follows:
(function($){
jQuery.fn.auto_input = function(){
$(this).children("input").keypress(InsertInput);
$(this).children("a:first").hide();
}
function InsertInput(){
var target = $(this).parent("div");
var input = target.clone();
if($(target).next().html()=='' ||$(target).next().html()===null){
input.insertAfter(target); input.find("input").keypress(InsertInput).val(""); input.find("a").show().click(function(){ input.remove();
});
}
}
})(jQuery);
make this as seperate js file and import.
now you have to write it on your main html/js file where all other works are done like as follows:
$(document).ready(function(){
$(".any_classname").auto_input();
})
now, we are done. start trying it. write something on the existing textbox, a new one will be created which can also be closed by clicking the x. you can also change the template by replacing 'x' with your own image, nothing will differ.
Subscribe to:
Post Comments (Atom)










1 comments:
generate input name are duplicate (txtAuthor2)
how do i change it to autoincrement like txtAuthor3 , txtAuthor4....
Post a Comment