简体   繁体   English

在php文件中动态添加或删除输入字段

[英]Add or delete input fields dynamically in a php file

I'm currently trying to add a plus and minus feature to a webpage in a CMS. 我目前正在尝试在CMS的网页中添加正负功能。 The plus would add a clone of an input field that would appear on the webpage. 加号将添加将显示在网页上的输入字段的副本。 The minus would delete the respective input field. 减号将删除相应的输入字段。 So far i have been able to manually add fields through the code of the webpage itself. 到目前为止,我已经能够通过网页本身的代码手动添加字段。 The added ones are basically a complete copy and paste of the original field. 添加的内容基本上是原始字段的完整副本和粘贴。 The only problem with this is when i select an option for the additional ones it does not stick upon page refresh. 唯一的问题是,当我为其他选项选择一个选项时,它不会在页面刷新时停留。 All the fields just equal whichever the last one was set to. 所有字段均相等,即最后一个字段为准。

Here is the relevant code: 以下是相关代码:

 <?php 



if ( ! module_config::can_i( 'edit', 'Settings' ) ) {
    redirect_browser( _BASE_HREF );
}

if ( isset( $_REQUEST['extra_default_id'] ) && $_REQUEST['extra_default_id'] ) {
    $show_other_settings = false;
    $extra_default       = module_extra::get_extra_default( $_REQUEST['extra_default_id'] );
?>
<form action="" method="post">
<input type="hidden" name="_process" value="save_extra_default">
<input type="hidden" name="extra_default_id" value="<?php echo (int) $_REQUEST['extra_default_id']; ?>"/>
<?php
$fieldset_data = array(
    'heading'  => array(
        'type'  => 'h3',
        'title' => 'Edit Extra Default Field',
    ),
    'class'    => 'tableclass tableclass_form tableclass_full',
    'elements' => array(
        array(
            'title' => 'Name/Label',
            'field' => array(
                'type'  => 'text',
                'name'  => 'extra_key',
                'value' => $extra_default['extra_key'],
            ),
        ),
        array(
            'title' => 'Table',
            'field' => array(
                'type'  => 'html',
                'value' => $extra_default['owner_table'],
            ),
        ),
    )
);
switch($extra_default['owner_table']){
    case 'customer':

        $fieldset_data['elements'] [] = array(
            'title' => 'Customer Type1',
            'field' => array(
                'type'    => 'select',
                'name'    => 'owner_table_child',
                'value'   => $extra_default['owner_table_child'],
                'options' => module_customer::get_customer_types(),
                'options_array_id' => 'type_name',
                'blank'   => ' - All - ',
                'help'    => 'Default will display the extra field when opening an item (eg: opening a customer). If a user can view the customer they will be able to view the extra field information when viewing the customer. Public In Column means that this extra field will also display in the overall listing (eg: customer listing). More options coming soon (eg: private)',
            ),
        );

        $fieldset_data['elements'] [] = array(
            'title' => 'Customer Type2',
            'field' => array(
                'type'    => 'select',
                'name'    => 'owner_table_child2',
                'value'   => $extra_default['owner_table_child2'],
                'options' => module_customer::get_customer_types(),
                'options_array_id' => 'type_name',
                'blank'   => ' - All - ',
                'help'    => 'Default will display the extra field when opening an item (eg: opening a customer). If a user can view the customer they will be able to view the extra field information when viewing the customer. Public In Column means that this extra field will also display in the overall listing (eg: customer listing). More options coming soon (eg: private)',
            ),
        );

        $fieldset_data['elements'] [] = array(
            'title' => 'Customer Type3',
            'field' => array(
                'type'    => 'select',
                'name'    => 'owner_table_child3',
                'value'   => $extra_default['owner_table_child3'],
                'options' => module_customer::get_customer_types(),
                'options_array_id' => 'type_name',
                'blank'   => ' - All - ',
                'help'    => 'Default will display the extra field when opening an item (eg: opening a customer). If a user can view the customer they will be able to view the extra field information when viewing the customer. Public In Column means that this extra field will also display in the overall listing (eg: customer listing). More options coming soon (eg: private)',
            ),
        );



        break;
}

FYI this is not my original code. 仅供参考,这不是我的原始代码。 "Customer Type1" is the original field 2 and 3 are just copy and pastes. “客户类型1”是原始字段2,而字段3仅是复制和粘贴。 If someone can help me have it so that each one will have its own unique value that would be helpful. 如果有人可以帮助我,让每个人都有自己独特的价值,那将是有帮助的。

To achieve the desired functionality i suspect i will link it to a JavaScript file to create the dynamic + and minus functionality. 为了实现所需的功能,我怀疑我会将其链接到JavaScript文件以创建动态+和减号功能。 If someone can direct me to how to achieve that in JavaScript from a conceptual basis that would be appreciated. 如果有人可以指导我从概念的角度实现JavaScript的方法,将不胜感激。

Also here is a screenshot of the whole page so you can get a better idea of what is going on. 另外,这里是整个页面的屏幕截图,因此您可以更好地了解正在发生的事情。

在此处输入图片说明

So in short here are my questions in priority order: 简而言之,这是我按优先顺序排列的问题:

  • How can I create additional fields that will not be wiped away upon page refresh and will be successfully applied. 如何创建其他字段,这些字段不会在页面刷新时消失,而是会成功应用。
  • What is the best way to acheive the plus and minus functionality. 实现加减功能的最佳方法是什么。

This can be achieved in various different ways. 这可以通过各种不同的方式来实现。 But, let me propose you an approach which uses jQuery and localStorage . 但是,让我为您提出一种使用jQuerylocalStorage

Let's say you have an HTML input block which looks like this, 假设您有一个HTML输入块,看起来像这样,

在此处输入图片说明

When you click on Add button, it duplicates the input block with its values, like this, 当您单击“添加”按钮时,它将复制输入块及其值,如下所示,

在此处输入图片说明

And the remove button, will remove the entire block (with Add and Remove buttons). 删除按钮将删除整个块(带有“添加”和“删除”按钮)。

If I got your question clear (if not, with a little tweak) you can make use of browser's localStorage to keep these actions (rows and data) saved and retrieve it while refreshing the page. 如果我的问题很清楚(如果没有,请稍作调整),则可以利用浏览器的localStorage保留这些操作(行和数据),并在刷新页面时将其检索。 So, the previously added rows and data won't get lost. 因此,先前添加的行和数据不会丢失。

A sample HTML (I am using Bootstrap4 in this sample), HTML示例 (在此示例中,我使用的是Bootstrap4),

<div class="container multi-input-area" style="width: 20%;">
        <div class="row p-3">
            <div class="col-12">
                <input type="text" name="inputfield[]" class="form-control" value=""/>              
                <button type="button" class="btn btn-primary add-btn">Add</button>              
                <button type="button" class="btn btn-secondary remove-btn">Remove</button>
            </div>
        </div>      
    </div>

Javascript block, Javascript块

A quick walkthrough, 快速演练

  1. If items not found in the localStorage or items length is zero, it will bring a default row, so users can add more rows. 如果在localStorage中找不到itemsitems长度为零,则将显示默认行,因此用户可以添加更多行。 (function initDefaultInputRow ). (函数initDefaultInputRow )。
  2. Every time user presses Add or Remove buttons, it scans the dom and add / remove to / from localStorage the current instance (I am assuming the value of input field is required so, I am adding that to the localStorage item). 每次用户按下“ Add或“ Remove按钮时,它都会扫描dom并将当前实例添加到localStorage或从本地存储中删除(我假设输入字段的value是必需的,因此我将其添加到localStorage项中)。
  3. When the user refreshes page, it checks for items key in the localStorage and iterate through and fill the page with input field blocks with values (functions prepareInputFields() and initDefaultInputRow() . 当用户刷新页面时,它将检查是否在localStorage中键入items ,并遍历页面,并使用值(函数prepareInputFields()initDefaultInputRow()输入字段块填充页面。
  4. Function getAllInputs() updates the current scenario (input rows and its values) to the localStorage. 函数getAllInputs()将当前方案(输入行及其值)更新为localStorage。

     var items = []; $(document).ready(function(){ prepareInputFields(); $(document).on('click', '.add-btn', function(){ $(this).closest('.row').clone().appendTo(".multi-input-area"); getAllInputs(); }); $(document).on('click', '.remove-btn', function(){ $(this).closest('.row').remove(); getAllInputs(); }); }); function getAllInputs() { items = []; $('.multi-input-area .row').each(function (){ var inputFieldVal = $(this).find('input').val(); var itemDetails = { 'value' : inputFieldVal }; items.push(itemDetails); }); localStorage.setItem('items', JSON.stringify(items)); } function prepareInputFields() { var lsItems = localStorage.getItem('items'); if (lsItems !== null) { jsDecode = JSON.parse(lsItems); var arrayLength = jsDecode.length; if (arrayLength === 0) { initDefaultInputRow(); } else { var newHtml = ''; for (var i = 0; i < arrayLength; i++) { var value = jsDecode[i].value; newHtml += '<div class="row p-3"><div class="col-12">'; newHtml += '<input type="text" name="inputfield[]" class="form-control" value="'+ value +'"/>' + '<button type="button" class="btn btn-primary add-btn">Add</button>' + '<button type="button" class="btn btn-secondary remove-btn">Remove</button>'; newHtml += '</div></div>'; } $('.multi-input-area').html(newHtml); } } else { initDefaultInputRow(); } } function initDefaultInputRow() { var html = '<div class="row p-3"><div class="col-12"><input type="text" name="inputfield[]" class="form-control" value=""/>'; html += '<button type="button" class="btn btn-primary add-btn">Add</button>'; html += '<button type="button" class="btn btn-secondary remove-btn">Remove</button></div></div>'; $('.multi-input-area').html(html); } 

    A fully working HTML file (combining above HTML and JS block). 完全正常工作的HTML文件 (在HTML和JS块上方组合)。 You can copy and paste following code into a HTML file and see it by yourself. 您可以将以下代码复制并粘贴到HTML文件中,然后自己查看。

     <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> </head> <body> <div class="container multi-input-area" style="width: 20%;"> <div class="row p-3"> <div class="col-12"> <input type="text" name="inputfield[]" class="form-control" value=""/> <button type="button" class="btn btn-primary add-btn">Add</button> <button type="button" class="btn btn-secondary remove-btn">Remove</button> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <script> var items = []; $(document).ready(function(){ prepareInputFields(); $(document).on('click', '.add-btn', function(){ $(this).closest('.row').clone().appendTo(".multi-input-area"); getAllInputs(); }); $(document).on('click', '.remove-btn', function(){ $(this).closest('.row').remove(); getAllInputs(); }); }); function getAllInputs() { items = []; $('.multi-input-area .row').each(function (){ var inputFieldVal = $(this).find('input').val(); var itemDetails = { 'value' : inputFieldVal }; items.push(itemDetails); }); localStorage.setItem('items', JSON.stringify(items)); } function prepareInputFields() { var lsItems = localStorage.getItem('items'); if (lsItems !== null) { jsDecode = JSON.parse(lsItems); var arrayLength = jsDecode.length; if (arrayLength === 0) { initDefaultInputRow(); } else { var newHtml = ''; for (var i = 0; i < arrayLength; i++) { var value = jsDecode[i].value; newHtml += '<div class="row p-3"><div class="col-12">'; newHtml += '<input type="text" name="inputfield[]" class="form-control" value="'+ value +'"/>' + '<button type="button" class="btn btn-primary add-btn">Add</button>' + '<button type="button" class="btn btn-secondary remove-btn">Remove</button>'; newHtml += '</div></div>'; } $('.multi-input-area').html(newHtml); } } else { initDefaultInputRow(); } } function initDefaultInputRow() { var html = '<div class="row p-3"><div class="col-12"><input type="text" name="inputfield[]" class="form-control" value=""/>'; html += '<button type="button" class="btn btn-primary add-btn">Add</button>'; html += '<button type="button" class="btn btn-secondary remove-btn">Remove</button></div></div>'; $('.multi-input-area').html(html); } </script> <body> 

I am giving you just a start so you can understand the concept / idea and move on with your very specific requirments. 我只是给您一个开始,这样您就可以了解概念/想法,并继续进行非常具体的要求。 I used localStorage as an example. 我以localStorage为例。 You can use Cookies if you like. 您可以根据需要使用Cookies。 I hope this helps you somewhat deciding which direction you need to move. 我希望这可以帮助您确定需要朝哪个方向移动。

Cheers 干杯

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

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