i am trying bellow jquery code to perform some dynamic changes to my front view to make the odoo switch toggle to behave like radio button.so it could be selected one at a time like radio button
Note: console.log("test") is working but the code with css selector is not working
please guide me how i run my script to work it fine
$(document).ready(function(){
$(".wk_checked_question").click(function(){
alert("you click me!");
});
console.log("test");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
*test.html**
<tbody>
<tr>
<td class="question_id" style="width:70%">Q1. t-shirt coler
size</td>
<td class="question_id" style="width:50%">$ 120.00</td>
<td><label class="switch">
input class="wk_checked_question" data-id="2" type="checkbox">
<span class="check_box round"></span>
</label>
</td>
</tr>
<tr>
<td class="question_id" style="width:70%">Q2. t-shirt size</td>
<td class="question_id" style="width:50%"> Free</td>
<td>
<label class="switch">
<input class="wk_checked_question" data-id="1" type="checkbox">
<span class="check_box round"></span>
</label>
</td>
</tr>
</tbody>
Maybe this is what you are looking for:
$(document).ready(function(){
$("body").on("click",".wk_checked_question",function(ev){
$(".wk_checked_question").each((i,cb)=>cb.checked=(cb==this));
this.checked=true; // a "real" radio button cannot be unchecked ...
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:500px">
<tbody>
<tr>
<td class="question_id" style="width:70%">Q1. t-shirt color size</td>
<td class="question_id" style="width:50%">$ 120.00</td>
<td><label class="switch"><input class="wk_checked_question" data-id="2" type="checkbox">
<span class="check_box round"></span></label></td>
</tr>
<tr>
<td class="question_id" style="width:70%">Q2. t-shirt size</td>
<td class="question_id" style="width:50%"> Free</td>
<td>
<label class="switch">
<input class="wk_checked_question" data-id="1" type="checkbox">
<span class="check_box round"></span></label></td>
</tr>
</tbody>
</table>
After a click on a checkbox the .each()
loop goes over all checkboxes with the same class and sets only the one being identical to the clicked ono (this
). All others are unchecked.
I used "delegated event attachment" with jQuery.on()
as suggested in @freedomn-m's comment. This has the advantage that it will work on target elements (.wk_checked_question
) that don't even exist at the time of the event attachment.
Your HTML was also missing the <table>
tags around your <tbody>
which I added.
Edit
Coming back to this answer I realized that I could simplify the script even further and allow for an option to be unselected again by using this:
$("body").on("click",".wk_checked_question",function(ev){
let newstate=this.checked;
$(".wk_checked_question").prop("checked",false);
this.checked=newstate
});