如何动态地通过jQuery更新隐藏的表单字段

时间:2012-08-11 22:51:10

标签: jquery dynamic hidden-field

我有一个隐藏的表单字段,用于存储jQuery UI可排序列表的值。

<input name="asw_options[asw_icon_order]" type="hidden" value="<?php echo $aswicons ?>" />

我有一个jQuery函数,可以保存排序列表的顺序。

/* Social Networking Icon Sorter */
var itemList = $('#asw-sortable');

itemList.sortable({
    update: function(event, ui) {
        $('#loading-animation').show(); // Show the animate loading gif while waiting

        opts = {
            url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php
            type: 'POST',
            async: true,
            cache: false,
            dataType: 'json',
            data:{
                action: 'item_sort', // Tell WordPress how to handle this ajax request
                order: itemList.sortable('toArray').toString() // Passes ID's of list items in  1,3,2 format

            },
            success: function(response) {
                $('#loading-animation').hide(); // Hide the loading animation
                //$('#asw_options[asw_icon_order]').val(itemList.sortable('toArray').toString()); // Update hidden field with new values
                $('input[name=asw_options[asw_icon_order]]').val(itemList.sortable('toArray').toString());
                return; 
            },
            error: function(xhr,textStatus,e) {  // This can be expanded to provide more information
                alert(e);
                // alert('There was an error saving the updates');
                $('#loading-animation').hide(); // Hide the loading animation
                return; 
            }
        };
        $.ajax(opts);
    }
}); 

存储的数据保存如下:

美味,的Twitter,Facebook,GOOGLEPLUS,StumbleUpon公司,Pinterest的,LinkedIn,YouTube的

一切运转良好。您重新排序字段,并通过jQuery自动保存。

我的问题是上面存储的隐藏字段,我需要能够在jQuery成功完成订单的新保存后通过jQuery动态更新。

这是一个WordPress插件,所以我需要更新隐藏的输入字段,因为如果用户点击“保存”按钮,它会保存旧值,因为这是隐藏字段的初始“值”。

正如您在jQuery代码中看到的那样,我认为我可以将代码添加到“Success”函数中,然后更新隐藏字段,但是它不起作用。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你的选择器中缺少一些引号,试试这个:

$('input[name="asw_options[asw_icon_order]"]').val(itemList.sortable('toArray').toString());