为动态字段分配增量值 [英] Assigning an increment value to dynamic fields

查看:61
本文介绍了为动态字段分配增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从jquery函数生成的动态输入字段。可以通过按钮单击这些输入字段来添加或删除。这些字段填充了mysql表中的数据。每个填充的输入都具有从DB获取的唯一ID。添加新字段时,我从ajax请求中获取下一个 AUTO_INCREMENT 。然后我可以增加+1但是对于所有字段。我只想为新字段做这个。如果由于某种原因从另一个应用程序进行插入查询事务,它将从字段更新开始增量,然后用正确的值更新其余的(检查我的意思是什么意思jsFiddle ( http://jsfiddle.net/f9XP8/2/ )。

I have dynamic input fields generated from a jquery function. There is the ability to add or delete through button clicks these input fields. The fields are populated with data from mysql table. Each populated input has a unique ID fetched from the DB. When adding a new field I am getting the next AUTO_INCREMENT from an ajax request. I am then able to increment +1 but for all fields. I only want to do this for the new fields. If by some reason an insert query transaction is made from another app it will update start increment from field and then update the rest with the correct values (check to see what I mean jsFiddle(http://jsfiddle.net/f9XP8/2/).

问题是如何将它们放在一起。我只想跟随能够添加一个新字段并为其分配适当的下一个 person_id for db insert. 实际示例

The problems is how to put it all together. I just want to follow to able to add a new field and assign it the appropriate next person_id for db insert. LIVE EXAMPLE

<script>
$(document).ready(function () {
    var $increment_num = $('#increment_num');
    var interval = 100;  //3000 = 3 seconds
    function doAjax() {
        $.ajax({
            type: 'POST',
            url: 'personAutoIncrement.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (data) {
                    var $cloned = $('#input_table tr');
                    var num = parseInt(data);
                    $increment_num.val(num);
                    $cloned.each(function(i){
                        $(this).find('[name^="increment_id"]').first().val(num+i);
                    })
            },
            complete: function (data) {
                // Schedule the next
                setTimeout(doAjax, interval);

        }
    });
    }
    setTimeout(doAjax, interval);
    var click_count = 0;
    $('#btnAdd').click(function () {
    click_count++;
        var $clones     = $('#input_table tr'),
            num         = $clones.size() + 1,
            next_num    = parseInt($clones.last().find('input[name^="increment_id"]').val()) + 1,
            $template   = $clones.first(),
            newSection  = $template.clone().attr('id', 'pq_entry_'+num),
            ident       = 'increment_id_'+num;
            person_id = 'person_id_'+num;
            person_fname = 'person_fname_'+num;
            person_lname = 'person_lname_'+num;

        // clear out all sections of new input
        newSection.find('input').not('[name^="increment_id"]').val('');

        newSection.find('input[name^="increment_id"]').attr({
            'id': ident,
            'name': ident
        }).val(/*next_num*/);
        newSection.find('input[name^="person_id"]').attr({
            'id': person_id,
            'name': person_id
        }).val(/*next_num*/);
        newSection.find('input[name^="person_fname"]').attr({
            'id': person_fname,
            'name': person_fname
        }).val(/*next_num*/);


        $('#input_table').append(newSection);
        $('#btnDel').prop('disabled', '');
        if (num == 100) $('#btnAdd').prop('disabled', 'disabled');
    });

    $('#btnDel').click(function () {
        var num = $('.clonedSection').length; // how many duplicate input fields we currently have
        $('#pq_entry_' + num).remove(); // remove the last element

        // enable the "add" button
        $('#btnAdd').prop('disabled', '');

        // if only one element remains, disable the "remove" button
        if (num - 1 == 1) $('#btnDel').prop('disabled', 'disabled');
    });

    $('#btnDel').prop('disabled', 'disabled');
});
</script>

html

<table>
    <thead>
        <tr>
            <th>ID from DB</th>
            <th>First Name</th>
        </tr>
    </thead>
    <tbody id="input_table">
        <tr id="pq_entry_1">
            <td><input type="text" id="increment_id_1" name="increment_id_1" readonly value="5" /></td>
            <td><input type="text" name="first_name" placeholder="First Name" /></td>
        </tr>
    </tbody>
</table>
<input type='button' id='btnAdd' value='add text box' />
<input type='button' id='btnDel' value='Delete' /></br>
</table>

推荐答案

如果我没弄错,你想知道如何增加某些行,但允许其他人冻结(因为它们被保存到数据库中)。我已经更改了你的代码,这里有重要的注释:

If I'm not mistaken, you are wanting to know how to increment certain rows, but allow others to be "frozen" (because they are saved to the database). I have changed your code a bit more, here are the important notes:


  1. 我删除了动态名称属性。您不需要动态生成字段名称,您只需指定data- *属性来保存id或引用 tr.find('input [name =person_id]')

  2. tr 中添加了数据保存的属性知道它是否应该包含在更新的自动增量ID 中,或者它是否应该保持原样

  3. 添加了保存每行旁边的按钮,因为它只是在行上设置数据保存的属性,如果需要,可以添加一个AJAX调用来保存记录

  1. I removed the dynamic name attributes. You don't need to dynamically generate field names, you can just assign data-* attributes to hold the id or refer to tr.find('input[name="person_id"]')
  2. Added a data-saved attribute to the tr to know whether or not it should be included in the updated auto increment id or if it should just stay as it is
  3. Added a save button next to each row, which as it is just sets the data-saved attribute on the row, you can add an AJAX call to save the record if you want

更新小提琴

Javascript:

The Javascript:

$(document).ready(function () {
    var $increment_num = $('#increment_num');
    var interval = 5000;  //3000 = 3 seconds
    function doAjax() {
        $.ajax({
            type: 'POST',
            url: 'personAutoIncrement.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (data) {
                var $cloned = $('#input_table tr').not('[data-saved]');
                var num = parseInt(data);
                $increment_num.val(num);
                $cloned.each(function(i){
                    var $this = $(this);
                    $this.find('[name^="person_id"]').first().val(num+i);
                })
            },
            complete: function (data) {
                // Schedule the next
                setTimeout(doAjax, interval);
            }
        });
    }
    setTimeout(doAjax, interval);
    var click_count = 0;

    $('#btnAdd').click(function () {
        click_count++;
        var $clones     = $('#input_table tr'),
            num         = $clones.size() + 1,
            next_num    = parseInt($clones.last().find('input[name^="person_id"]').val()) + 1,
            $template   = $clones.first(),
            newSection  = $template.clone().attr('id', 'pq_entry_'+num),
            person_id   = 'person_id_'+num;
            person_fname = 'person_fname_'+num;
            person_lname = 'person_lname_'+num;

        newSection.removeAttr('data-saved');

        // clear out all sections of new input
        newSection.find('input[type="text"]').val('');

        newSection.find('input[name^="person_id"]').attr({
            'id': person_id
        }).val(next_num);

        newSection.find('input[name^="person_fname"]').attr({
            'id': person_fname
        });

        newSection.find('input[type="button"]').attr('data-ident', next_num);


        $('#input_table').append(newSection);
        $('#btnDel').prop('disabled', '');
        if (num == 100) $('#btnAdd').prop('disabled', 'disabled');
    });

    $('.save-button').click(function(){
        var $parent = $(this).parents('.clonedSection')
        var id = $parent.find('input[name="person_id"]').val();
        // do whatever else here, save to db
        $parent.attr('data-saved', '1');
    })

    $('#btnDel').click(function () {
        var num = $('.clonedSection').length; // how many duplicate input fields we currently have
        $('#pq_entry_' + num).remove(); // remove the last element

        // enable the "add" button
        $('#btnAdd').prop('disabled', '');

        // if only one element remains, disable the "remove" button
        if (num - 1 == 1) $('#btnDel').prop('disabled', 'disabled');
    });

    $('#btnDel').prop('disabled', 'disabled');
});

HTML:

<form>
<strong>Start Increment from Next ID to be inserted in the DB:</strong><input id="increment_num" name="increment_num"  type="text" /></br>
<table>
    <thead>
        <tr><th>ID from DB</th><th></th>
        <th>First Name</th></tr>
    </thead>
    <tbody id="input_table" >
        <tr id="pq_entry_1" class="clonedSection" data-saved="1">
            <td><input type="text" name="person_id" value='1' readonly /></td>
            <td><input id="person_fname_1" name="person_fname" placeholder=" First Name" type="text" value='James'/></td>
            <td><input type="button" class="save-button" value="Save" />
        </tr>
        <tr id="pq_entry_2" class="clonedSection" >
            <td><input type="text" name="person_id" value='2' readonly /></td>
            <td><input id="person_fname_2" name="person_fname" placeholder=" First Name" type="text" value='Cynthia'/></td>
            <td><input type="button" class="save-button" value="Save" />
        </tr>
    </tbody>
</table>
<input type='button' id='btnAdd' value='add another Person' />
<input type='button' id='btnDel' value='Delete' /></br>
</form>

说完所有这些后,我可能会通过隐藏元素来解决这个问题:

Having said all of that, I probably would approach this differently by having a hidden element:

< input type =hiddenname =person_idvalue =1/>

当生成新行时无效:

< input type =hidden name =person_idvalue =/>

然后在我的PHP中,我会允许MySQL处理自动递增id这样的方式:

Then in my PHP, I would allow MySQL to handle auto incrementing the id in a manner like this:

<?php
    $params = $_POST;
    if(is_numeric($params['person_id'])){
       $sql = sprintf('UPDATE person SET fname = "%s", lname = "%s" WHERE person_id = %u LIMIT 1', 
          mysql_real_escape_string($params['fname']), 
          mysql_real_escape_string($params['lname']), 
          intval($params['person_id'])
       );
    } else {
       // the NULL tells MySQL to select the correct next increment id automatically
       $sql = sprintf('INSERT INTO person (id, fname, lname) VALUES (NULL, "%s", "%s")',
         mysql_real_escape_string($params['fname']),
         mysql_real_escape_string($params['lname']);
       );
    }

?>

这篇关于为动态字段分配增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆