Mikhah Mikhah - 3 months ago 9
HTML Question

Jquery change only one paragraph by clicking the chekbox

So I have a checkbox and a paragraph in my rails app -

<li class="task" id="task_<%= task.id %>" >
<%= check_box_tag task.id, task.id, task.mark, class: "task-check" %>
<label for=<%=task.id %> ></label>
<p><%= task.content %></p>


And I want to toggle paragraphs' class by clicking on the checkbox

I've write some Jquery function to change task status (that's not so important,but maybe you'll want to know it) and to toggle the class -

$(".task-check").on('click', function(){
$.ajax({
url: '/tasks/'+this.value+'/mark',
type: 'POST',
data: {"mark": this.checked}
});
$('p').toggleClass('done')
});


But it changes all paragraph on the page,so I'm missing
this
as I think,but I can't figure out where should I put
this

Answer

Updated

$(".task-check").on('change', function(){
    // always cache the element, this increase the performance,
    // also in javascript, `this` is too tricky and may change inside blocks
    // so by caching, you can always trust chached item
    var $this = $(this);

    $.ajax({
        url: '/tasks/'+ $this.val() +'/mark',
        type: 'POST',
        data: {"mark": $this.is(':checked') }
    });

    $this.next().toggleClass('done');
    // OR if `p` isn't next item (if so, maybe you should add `class` to p,
    // so you can find that easily)
    // $this.parent().find('p.MY-CLASS').toggleClass('done');
});
Comments