Mikhah Mikhah - 1 year ago 81
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(){
url: '/tasks/'+this.value+'/mark',
type: 'POST',
data: {"mark": this.checked}

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

Answer Source


$(".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);

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

    // 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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download