Generating list item x number of times, based on user input

限于喜欢 提交于 2019-12-11 04:56:55

问题


I have a basic unordered list with an input field/form below it. I would like the user to be able to type in the total number of list items they would like to see and on click, the results would show. Here is my HTML:

<div id="boxes">
    <div class="box1"></div>
    <div class="box1"></div>
    <div class="box1"></div>
    <div class="box1"></div>
    <div class="box1"></div>
</div>

<form id="four" action="#">
    <input type="text" placeholder="Type items per page"></input>
    <button>Submit</button>
</form>

And my JQuery:

$("#four button").on('click', function(){
    var buttonValsss = $("#four input").val();
    var boxes = $("#boxes");
    var generate = "<div class='box1'></div>";

    boxes.html('');
    boxes.append(generate);
    boxes.children().html("<p>" + text + "</p>");
});

I am storing the variable from the user input (number of items), clearing out all of the list items in #boxes, and then appending one list item on click, setting the text from a global variable from a previous function. On click, I want the variable generate to be appended x number of times, as defined by the variable buttonValsss

What is the best way to go about this?


回答1:


try using for loop:

$("#4 button").on('click', function(){
    var buttonValsss = $("#4 input").val();
    var boxes = $("#boxes");
    boxes.empty(); // you can use empty() method    
    for (i = 0; i < buttonValsss; i++ ) {
        boxes.append('<div class="box1"></div>');
    }
});

http://jsfiddle.net/z2Wc3/



来源:https://stackoverflow.com/questions/11286407/generating-list-item-x-number-of-times-based-on-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!