How to generate dynamic elements using jQuery?
How can I generate dynamic html elements using jQuery? Is it possible to remove it on button click? i.e. I have to generate textbox on button click and contain of textbox is going to display in one label. Like this:
http://jsfiddle.net/kDSQa/5/
User can add upto 3 emails. And by clicking delete button the generated textbox will be deleted. How can I do that?
I have referred to this: how can i get id/ generate id of dynamically generated elements in html using jquery?开发者_如何学编程 thread
any suggestion?
I think you want something like - http://jsfiddle.net/rifat/NGgSB/
Though there are other ways to do it :)
create a document.createElement()
and use $().appendTo()
to add it and $().remove()
to obviously remove it
You can create new elements by passing the HTML as a string to jQuery, so for example, this:
$('<tr><input type="text" id="email2"/><input type="button" id="add2"/></tr>')
Returns a jQuery wrapper object holding a tr that contains two input elements. You can then use jQuery methods like append or appendTo to add these dynamically created elements into the appropriate location in your document.
However, in this particular case, it looks like you want the add button to effectively copy some existing elements, give them unique ids, then add them into the document. You could do that by using the jQuery.clone method to duplicate the desired elements, use the attr or prop method to change the ids to something unique, then use append, appendTo, etc., to insert the cloned elements at the appropriate point in the document.
精彩评论