John John - 7 months ago 24
Javascript Question

jQuery - Add Remove Class - Set Value Of Input

Hi I need this to Add Remove Classes & Set Value of nextAll input.

I can make it work but it only works for one time. I need it to be more like a toogle.



$(document).ready(function () {
$(".fa-circle").click(function () {
$(this).nextAll('input').first().val('Yes');
$(this).removeClass("fa-circle light_gray").addClass("fa-check green");
});
$(".fa-check").click(function () {
$(this).nextAll('input').first().val('No');
$(this).removeClass("fa-check green").addClass("fa-circle light_gray");
});
});

.green {
color: #8FCE35;
}

.light_gray {
color: #DDDDDD;
}

.point {
cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table class="candi_elections_table" align="center" style="text-align: left;">
<tbody>
<tr>
<td>198</td>
<td>
<span class="fa-check font16 green point">CLICK HERE</span>
<input id="198" class="" type="text" data-tooltip="" data-load-state="" data-inputmask="" style="" title="" placeholder="" value="" name="198" vk_11844="subscribed">
</td>
<td>Something 1</td>
</tr>
<tr>
<td>200</td>
<td>
<span class="fa-circle font16 light_gray point">CLICK HERE</span>
<input id="200" class="" type="text" data-tooltip="" data-load-state="" data-inputmask="" style="" title="" placeholder="" value="" name="200" vk_11844="subscribed">
</td>
<td>Something 2</td>
</tr>
<tr>
<td>201</td>
<td>
<span class="fa-check font16 green point">CLICK HERE</span>
<input id="201" class="" type="text" data-tooltip="" data-load-state="" data-inputmask="" style="" title="" placeholder="" value="" name="201" vk_11844="subscribed">
</td>
<td>Something 3</td>
</tr>
<tr>
<td>202</td>
<td>
<span class="fa-circle font16 light_gray point">CLICK HERE</span>
<input id="202" class="" type="text" data-tooltip="" data-load-state="" data-inputmask="" style="" title="" placeholder="" value="" name="202" vk_11844="subscribed">
</td>
<td>Something 4</td>
</tr>
</tbody>
</table>





Anyone can see what i am doing wrong?


  • the fa-check & fa-circle are awesome fonts



I also got it in jsfiddle
https://jsfiddle.net/9bonuyyn/1/

Answer

You need event delegation for dynamically added class. And also you can shorten your js like following.

$('.candi_elections_table').on("click", ".fa-circle, .fa-check", function () {
    if ($(this).hasClass('fa-circle')) {
        $(this).nextAll('input').first().val('Yes');
    } else {
        $(this).nextAll('input').first().val('No');
    }
    $(this).toggleClass("fa-check green fa-circle light_gray");
});

UPDATED FIDDLE