views:

188

answers:

2

I am currently trying to hook up jQuery UI dialog so that I may use it to create new items to my page and to modify ones existing already on the page. I managed in the former. I'm currently struggling in the latter problem, however. I just cannot find a nice way to pass the item to modify to the dialog.

Here's some code to illustrate the issue better. Note especially the part marked with XXX. The {{}} parts are derived from Django template syntax:

$(".exercise").click(function() {
    $.post("{{ request.path }}", {
            action: "create_dialog",
            exercise_name: $(this).text()
        },
        function(data) {
            $("#modify_exercise").html(data.content);
        },
        "json"
    );

    $("#modify_exercise").dialog('open');
});

$("#modify_exercise").dialog({
    autoOpen: false,
    resizable: false,
    modal: true,
    buttons: {
        '{% trans 'Modify' %}': function() {
            var $inputs = $('#modify_exercise :input');

            var post_values = {};
            $inputs.each(function() {
                post_values[this.name] = $(this).val();
            });

            post_values.action = 'validate_form';

            //XXX: how to get the exercise name here?
            post_values.exercise_name = 'foobar';

            $.post('{{ request.path }}', post_values,
                function(data) {
                    if( data.status == 'invalid' ) {
                        $('#modify_exercise').html(data.content);
                    }
                    else {
                        location.reload();
                    }
                },
                "json"
            );
        }
    }
});

Here's some markup to show how the code relates to the structure:

<div id="modify_exercise" class="dialog" title="{% trans 'Modify exercise' %}">
</div>

<ul>
    {% for exercise in exercises %}
        <li>
            <a class="exercise" href="#" title="{{ exercise.description }}">
                {{ exercise.name }}
            </a>
        </li>
    {% endfor %}
</ul>
+1  A: 

I can't think of how there is a connection between the clicked event and the dialog, so maybe the answer is just to use a global variable to store the name after each click event, and then use that in your dialog?

I've demonstrated this idea here: http://jsfiddle.net/NJa4U/

See how currentItem is used in that code.

Ryley
Global variable will do for now. Thanks. It would be nicer if a dialog had access to its "parent" element (the one that invoked it), though.
bebraw
A: 

Perhaps following might suit your taste better:

Before $("#modify_exercise").dialog('open');, add

$("#modify_exercise").data('exercise_name',$(this).text());

and in the button callback, replace post_values.exercise_name = 'foobar'; with

 post_values.exercise_name = $(this).data('exercise_name');
azatoth