Reputation: 7301
I have the following code-
<div class="service_box">
<div class="form">
<form class="cmxform">
<label>EL POS :</label>
<input type="checkbox">
<!-----------------------
multiple textboxes shall be added here as
<input type="text" class="someclass"> ---> textbox 1
<input type="text" class="someclass"> ---> textbox 2
------------------------>
<button id="add">Add</button>
</form>
</div>
</div>
I would like to add textbox(s) on the add button click event in jquery. Any help?
Upvotes: 2
Views: 19019
Reputation: 83
I have used something like this. It may be helpful
HTML :
<div class="filter_selector">
<input type="text">
<button class="remove_filter_category">-</button>
<button class="add_filter_category">+</button>
</div>
jquery:
$(document).ready(function() {
function updateFilterUI(){
$('.filter_selector .remove_filter_category').show();
$('.filter_selector .add_filter_category').hide();
$('.filter_selector .add_filter_category:last').show();
$('.filter_selector:only-child .remove_filter_category').hide();
}
updateFilterUI()
$('.filter_selector').on('click', '.add_filter_category', function () {
$('.filter_selector:last').after($('.filter_selector:last').clone(true));
updateFilterUI();
$('.filter_selector:last').find('input').val('');
return false;
});
$('.filter_selector .remove_filter_category').on('click', function () {
$(this).parent().remove();
updateFilterUI();
return false;
});
});
You can even test it in JSFIDDLE
Thanks.
Upvotes: 0
Reputation: 24648
The following code will enable you to both add text boxes and remove them, just in case you change your mind:
$(function() {
$('#add').on('click', function( e ) {
e.preventDefault();
$('<div/>').addClass( 'new-text-div' )
.html( $('<input type="textbox"/>').addClass( 'someclass' ) )
.append( $('<button/>').addClass( 'remove' ).text( 'Remove' ) )
.insertBefore( this );
});
$(document).on('click', 'button.remove', function( e ) {
e.preventDefault();
$(this).closest( 'div.new-text-div' ).remove();
});
});
Upvotes: 3
Reputation: 20646
Check this Demo Fiddle
$('.cmxform').append('<br/><input type="text" class="someclass"> ');
Use append() function to append an element dynamically to an element in the DOM.
Other options:
Depends where and how you wish to append the elements.
Upvotes: 1
Reputation: 62498
you can do it with jquery like this:
$("#add").click(function(event){
event.preventDefault();
$("input.someclass:first").clone(true).val("").appendTo(".cmxform");
});
clone()
will create copy of textbox after that reset it's value using val("")
and then append it to form using appendto()
Upvotes: 0