Create jQuery array of droppable elements

笑着哭i 提交于 2019-12-12 05:28:11

问题


I got draggable li - elements and droppable boxes - using jQuery UI.

My structure:

A list of 3 permission types

<ul>
    <li data-action="create">Create</li>
    <li data-action="edit">Edit</li>
    <li data-action="delete">Delete</li>
</ul>

And 3 areas to drop:

<div class="row">

    <div class="col-md-3 col-sm-6">
        <h3>Server</h3>
        <ul class="box" data-type="server"></ul>
    </div>

    <div class="col-md-3 col-sm-6">
        <h3>Games</h3>
        <ul class="box" data-type="games"></ul>
    </div>

    <div class="col-md-3 col-sm-6">
        <h3>User</h3>
        <ul class="box" data-type="user"></ul>
    </div>

</div>

I added data-type and data-action attributes for better handling. My current jQuery code for draggable and droppable:

$("#rights > ul > li").draggable({
    appendTo: "body",
    helper: "clone"
});

$("#rights ul.box").droppable({
    activeClass: "helperclass",
    hoverClass: "ui-state-hover",
    accept: ":not(.ui-sortable-helper)",
    drop: function(event, ui) {
        $(this).find(".placeholder").remove();
        $("<li></li>").html(ui.draggable.text() + '<span class="close">x</span>').appendTo(this);
    }
});

$("#rights").on('click', '.close', function () {
    $(this).parent().slideUp(200, function() { $(this).remove(); } );
});

This works perfect - but now i want to write the data in my MySQL DB. Perfect would be an array with strings like this:

server[create], user[edit] etc

So if submit i think i have to store all dropped elements in an array - but i don't know how to get them (then set it as value of hidden-field):

$('#userForm').submit(function() {
    $('#rights .box').each(function() {
        var currentBox = $(this).data('type');
        //Get all data-actions for this box 
    });
});

jsFiddle: http://jsfiddle.net/xw2djxdp/3/


回答1:


You can try this code:

var result = {};
    $('ul.box').each(function () {
        var type = $(this).attr('data-type');
        var elements = [];
        $(this).find('li').each(function () {
            elements.push($(this).text());
        });
        result[type] = elements
    });

Demo :http://jsfiddle.net/lotusgodkk/xw2djxdp/4/

Note: Click on the button and see the results in console



来源:https://stackoverflow.com/questions/27045084/create-jquery-array-of-droppable-elements

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