I’ve just got a jquery function working with my rails3 application. When a user clicks a checkbox on the page, it toggles the status and fades out:
$('#complete_task_1').click(function() {
$.ajax({
url: $(this).attr('href'),
type: 'get',
dataType: 'html',
success: function(data, textStatus, jqXHR) {
$('#complete_task_1').closest('tr').fadeOut();
},
error: function(data, status, error){
alert('Oooops!');
}
});
});
Initially I wanted to use $(this) instead of $(‘#complete_task_1’) but I couldn’t get that working. Right now, it’s all working fine.
My problem is that I need to reload the page manually after checking one box – otherwise, when I click another items checkbox, the js doesn’t seem to be called. It’s neither a success or error. There’s nothing in the dev log either.
Is there an easy way around this??
That issue is easy, it’s because
thisis determined by how a function is called, not where it’s defined. Since jQuery is calling yoursuccessfunction,thisis set by jQuery.You can tell jQuery what
thisshould be inside that callback via thecontextargument:…or since you’re already calling
$(this)once and I hate to see unnecessary duplication, you can use the scope you’re already closing over:You’re using an ID in your code, so you’re only ever hooking up one checkbox (since IDs must be unique on the page). My guess is that having updated the status, when you refresh the page that one checkbox now represents a different item.
Instead of using an ID selector, use a class selector or a structural selector matching all of your relevant checkboxes. It looks like you’re using an
hrefon the checkbox to differentiate them, so none of the code changes except the markup, and the initial selector.So if you wanted to use a class on the checkboxes:
Or if they’re all in a container, you could use a structural (in this case, descendant) selector:
Update: Here’s a complete working example (live copy):
HTML:
Those URLs just reply with
…or 2 or 3.
JavaScript:
Off-topic: It looks like you’re using an
hrefattribute on your checkboxes. That’s invalid HTML,hrefis not a valid attribute forinput[type=checkbox]. You might consider changing that todata-href, which would make it valid as of HTML5.