Currently what I have coded up works, but it seems rather crude. Basically here’s what I have (simplified):
JQuery ready:
<script type="text/javascript">
$(document).ready(function() {
$('div.partDelete').click(function() {
// TODO this seems like a dirty hack
var split = this.id.split('_');
if(split.length == 3) {
$('#part_id').val(split[0]);
alert($('#part_id').val());
$('#removePartForm').submit();
} else {
alert('There was a problem removing the selected part');
}
});
</script>
The form I am using:
<form id="removePartForm" action="{% url remove_part %}" method="post">
<input type="hidden" id="part_id" name="part_id" value="-1" />
{% for part in current_build.parts.all %}
<div id="{{ part.id }}_part_id" class="partDelete">remove</div>
{% endfor %}
</form>
All I’m trying to do is set the hidden input to take the part.id that has been selected by the user so that I can use it in my views.
For all I know this is the correct way to go about this, but I just have a feeling it isn’t. I am new to Django & JQuery so there may be some built in functionality for this that I haven’t found yet.
Thanks for any suggestions that you may have!
Solution (see mikaelb’s answer below)
Javascript:
$('div.partDelete').click(function() {
var selected_id =$(this).data("id");
$('#part_id').val(selected_id);
$('#removePartForm').submit();
});
HTML changes:
<div class="partDelete" data-id="{{ part.id }}">remove</div>
First of all; IDs shouldn’t start with a number (http://www.w3.org/TR/html4/types.html#type-name).
Aside from that, you’d typically use the data-* attribute for setting IDs to communicate with JS from server side. The data-* attribute can be anything you want. So data-foo=”” is a valid attribute.
Example:
HTML:
Javascript:
Hope this helps.
Edit: Moved comment to make it more clear, changed the example to be more specific to OP’s problem.