Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append the data only once using jquery

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>
like image 398
Jesivalar Avatar asked Dec 05 '22 23:12

Jesivalar


2 Answers

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

like image 121
Milind Anantwar Avatar answered Dec 28 '22 10:12

Milind Anantwar


    $(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?

like image 41
dumle Avatar answered Dec 28 '22 08:12

dumle