简体   繁体   English

限制字段​​集中的输入

[英]Limit the input in Fieldset

I am trying to create a section of my webstore where the customer can 'build' their own bundle and choose any combination of 5 items. 我试图在网上商店中创建一个部分,客户可以在其中“构建”自己的捆绑软件并选择5种商品的任意组合。

I have a set of buttons which, when clicked, add their value to a Fieldset along with a button to remove it in case they misclicked or changed their mind. 我有一组按钮,当单击它们时,会将它们的值添加到Fieldset中,并添加一个按钮以将其删除,以防万一他们误单击或改变了主意。

All the components work fine, but I don't know how to limit the Fieldset to only five items. 所有组件都可以正常工作,但是我不知道如何将Fieldset限制为仅五个项目。 Is there a way to either count the lines, then stop accepting input after five or look for 'Remove' five times? 有没有一种方法可以计算行数,然后在五点之后停止接受输入,或者寻找五次“删除”?

I'm still fairly new to coding and not too sure what is possible. 我对编码还很陌生,不太确定有什么可能。 This input will end up being submitted in a form. 此输入将最终以表格形式提交。

Here is my Fiddle and below is my Javascript code which i have tried for it : 这是我的小提琴 ,下面是我尝试过的Javascript代码:

$(document).ready(function () {
    $(".buttons").click(function () {
        var intId = $().length + 1;
        var item = $(this).html();
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
        var removeButton = $("<input type=\"button\" class=\"remove\" value=\"Remove\" />");
        removeButton.click(function () {
            $(this).parent().remove();
        });
        fieldWrapper.append(size);
        fieldWrapper.append(removeButton);
        $("#buildyourkit").append(fieldWrapper);
    });
});

This will give you the current quantity of elements added to the . 这将为您提供添加到中的当前元素数量。 Just make sure that there is still room for another before appending a new one. 只需确保在添加新的空间之前还有空间。

$("fieldset .fieldwrapper").length

I've forked your fiddle . 我把你的小提琴分叉了。 Just look at the console while adding new items to the fieldset. 在向字段集中添加新项目时,只需查看控制台即可。

You can have a global variable which will count up and disable all buttons if over 5 every time you add a field, and down and enable all buttons every time you remove a field. 您可以有一个全局变量,如果每次添加一个字段超过5 ,它将向上计数并禁用所有按钮,而每次删除一个字段则向下计数并启用所有按钮。

Also, it is a bit nicer to just set a live handler listening for any remove buttons, rather than make a new function and bind a new listener for each button, so I demonstrated; 而且,只设置一个实时处理程序侦听任何删除按钮,而不是创建一个新函数并为每个按钮绑定一个新的侦听器,会更好一些。 but it is not obligatory (your way works, too, given it's just 5 elements). 但这不是强制性的(考虑到只有5个元素,您的方法也行得通)。

$(document).ready(function () {
    var buttonMaxID = 0;
    var buttonCount = 0;
    $('$buildyourkit').on('click', '.remove', function () {
        $(this).parent().remove();
        if (buttonCount-- >= 5) {
            $('.buttons').prop('disabled', false);
        }
    });
    $(".buttons").click(function () {
        if (++buttonCount >= 5) {
            $('.buttons').prop('disabled', true);
        }
        var item = $(this).html();
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + (buttonMaxId++) + "\"/>");
        var removeButton = $("<input type=\"button\" class=\"remove\" value=\"Remove\" />");
        fieldWrapper.append(size);
        fieldWrapper.append(removeButton);
        $("#buildyourkit").append(fieldWrapper);
    });
});

What I propose is designing a manager class to maintain all functions/methods that must interact with the UI. 我建议设计一个经理类来维护必须与UI交互的所有功能/方法。 This allows you to define your data set in one place, and keep the UI binds in one place. 这使您可以在一个位置定义数据集,并将UI绑定保持在一个位置。 By doing so, you set yourself up with a cleaner code base, easy refactoring, and quickly make code modifications. 这样,您可以使用更简洁的代码库,轻松的重构并快速进行代码修改来设置自己。 Also, you get all this goodness without any global variables, another great bonus. 而且,您无需任何全局变量即可获得所有这些好处,这是另一个巨大的好处。

The code does look like its larger, but once you understand the simplicity of the manager you will see the possibilities I outlined above. 该代码看起来确实更大,但是一旦您了解了管理器的简单性,您就会看到我上面概述的可能性。

$(document).ready(function () {
    //Create a new Kit Manager
    var kitManager = new KitManager();

    $(".buttons").click(function () {
        kitManager.add(this);
    });

    $(".report").click(function () {
        kitManager.getKit();
    });
});

function KitManager()
{
    //Static amount of items to return
    var MAX_ITEMS = 5;
    //Where the items should be visually displayed on the UI
    var kitLegend = $("#buildyourkit");
    //Internal array for storing the items added
    var items = []

    function add(element)
    {       
        if(items.length < MAX_ITEMS)
        {
            var itemNumber = items.length + 1;         
            var item = $(element).html();
            var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + itemNumber + "\"/>");
            var removeButton = $("<input type=\"button\" class=\"remove\" value=\"Remove\" />"); 

            //Add item to the array collection
            items.push(item);

            //Bind a remove function to the newly created button
            removeButton.click(function () {
                kitLegend[0].removeChild(fieldWrapper[0]);
                items.splice(itemNumber, 1); 
            });

            //Append UI components to container
            fieldWrapper.append(item).append(removeButton);

            //Append to main legend
            kitLegend.append(fieldWrapper); 
        }
        else
        {
            //Simple alert to user
            alert('You\'ve Reached The Maximum Number of Items');
        }
    }
    //Simple function for demonstration of a reporting feature
    //or potential method for returning the stored items
    function getKit()
    {
        for(var i=0,length=items.length;i <length;i++)
        {
            console.log(items[i]);
        }
    }

    //Expose public method call
    return {
        add:add,
        getKit: getKit
    };
}

http://jsfiddle.net/x97S5/ http://jsfiddle.net/x97S5/

I hope you find the solution acceptable, and if you have any further questions please ask. 希望您认为该解决方案可以接受,如果还有其他问题,请询问。

For more information on the solution and technique proposed take a look at Key Principles of Maintainable JavaScript 有关建议的解决方案和技术的更多信息,请查看可维护JavaScript的关键原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM