How to pass a parameter to jQuery UI dialog event handler?
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');
});
$("#modi开发者_开发百科fy_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>
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');
if you're working with eventhandlers you might want to use the event object instead of some global var ;)
event.target is what you're looking for.
e.g.
$('.sel').bind('dialogcreate', function(event, ui) {
event.target.innerHTML = 'new content';
});
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.
精彩评论