In jquery,how to append the data(Textbox,dropdown) only once when click the button and also bind the those data with in a div tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test weekpicker</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function() {
$('.add_child').click(function() {
$div_open = $('<div id="container">');
$input1 = $('<input type="text" placeholder="Child Name" />');
$input2 = $('<select name="gender"><option value="0">Male</option><option value="1">Female</option></select>');
$div_close = $('</div>');
$('.append_child').append($div_open);
$('.append_child').append($input1);
$('.append_child').append($input2);
$('.append_child').append($div_close);
});
});
</script>
</head>
<body>
<div id="content">
<input type="button" class="add_child" value="Add child">
<div class="child_details">
<div class="append_child"></div>
</div>
</div>
</body>
</html>
You can use jquery .one() in this situation.
Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
You would also need to change the append logic to append input and select inside div with id container in .append_child
div. soemthing like this:
$('.add_child').one('click',function() {
$div_open = $('<div id="container"></div>');
$input1 = $('<input type="text" placeholder="Child Name" />');
$input2 = $('<select name="gender"><option value="0">Male</option><option value="1">Female</option></select>');
$('.append_child').append($div_open);
$('.append_child #container').append($input1);
$('.append_child #container').append($input2);
});
Working Demo
$(function() {
$('.add_child').click(
function() {
html = '<div class="container">'+
' <input type="text" placeholder="Child Name" />'+
' <select name="gender">'+
' <option value="0">Male</option>'+
' <option value="1">Female</option>'+
' </select>'+
'</div>';
$('.append_child').append(html);
$(this).unbind("click");
}
);
});
This is one way of doing it... not sure if this is what you want?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With