output appended HTML form elems and vals within <ul> <li> ... </li></ul>

I am currently, using jQuery .clone(); to grab current HTML form element values (that have been inserted or toggled by user) and then appending to my .results div element.

Basically user fills out form -> can click 'add button' -> form values appear within .results div (and previous most recent line that was added or cloned removed, when .remove button clicked).

I am trying to output each set (set meaning each time, .add was hit) within <ul> and <li> tags so it will output neater, and I'll have more control of outputs. I attempted to add this within the same '.appendTo' but was not correct.


$(document).ready(function() {
    checkRemove()
    $('.add').click(function() {
        $('input[type=text], input[type=checkbox], option:selected').clone().appendTo('.results');
        checkRemove();
    });
    $('.remove').click(function() {
        $('input[type=text]:last, input[type=checkbox]:last, option:selected').remove();
        checkRemove();
    });
});
function checkRemove() {
    if ($('input[type=text]').length == 1) {
        $('.remove').hide();
    } else {
        $('.remove').show();
    }
};

Again, the above is working. I would just like the outputs to occur within <ul><li></li></ul> HTML tags; so it is cleaner, and easier to style. Currently it is outputting via .appendTo directly within .results div without format.

Answers 1

  • This is the crux. add a empty ul tag

    $('.result').html("<ul class='mylist'></ul>");
    

    Append a li tag to that list and then add your clone!

    $('.mylist').append($('<li>')).append("");
            $('.allinputs input[type=text],.allinputs input[type=checkbox], option:selected').clone().appendTo($('.mylist li:last-child'));;
    

    May be you need to modify according to your requirement.

    $(document).ready(function() {
    	$('.result').html("<ul class='mylist'></ul>");
         checkRemove();
        $('.add').click(function() {
        	$('.mylist').append($('<li>')).append("");
            $('.allinputs input[type=text],.allinputs input[type=checkbox], option:selected').clone().appendTo($('.mylist li:last-child'));;
            
            checkRemove();
        });
        $('.remove').click(function() {
            $('input[type=text]:last, input[type=checkbox]:last, option:selected').remove();
            checkRemove();
        });
    });
    function checkRemove() {
        if ($('input[type=text]').length == 1) {
            $('.remove').hide();
        } else {
            $('.remove').show();
        }
    };
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="allinputs">
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <button class="add">click</button>
    </div>
    Result<br/>
    <div class="result"></div>

    Hope this helps!


Related Articles