Reputation: 11
Please Read this problem carefully.
I want the checkbox value checked when the span text is "True" on pageLoad. the below example works perfectly on radio button click then span value goes to "true" or "false".
Code
$('table').on('change', ':radio', function () {
$(this).next('span').text('True').closest('td')
.siblings().find('span').text('False');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td> <input type='radio' name='attandance' ><span>False</span></td>
<td> <input type='radio' name='attandance' ><span>False</span></td>
<td> <input type='radio' name='attandance' ><span>False</span></td>
</tr>
</table>
I want if the span value is true then the radio button automatically checked. Here is Attachment
Thanks.
Upvotes: 0
Views: 220
Reputation: 642
@faizan as i can see you have the function ready for onchange & you just need values to be changed on page/document load.
I suggest you can use $(document).ready()
function.
Below $(document).ready()
function will automatically set radio button checked when there will be a true value found.
$('table').on('change', ':radio', function () {
$(this).next('span').text('True').closest('td')
.siblings().find('span').text('False');
});
// Page load event to checked the true value
$(document).ready(function(){
$("table td").each(function(i, obj){
var value = $(obj).find("span").text();
if(value === "True"){
$(obj).find("input[type='radio']").prop("checked",true);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td> <input type='radio' name='attandance' ><span>False</span></td>
<td> <input type='radio' name='attandance' ><span>True</span></td>
<td> <input type='radio' name='attandance' ><span>False</span></td>
</tr>
</table>
And I would suggest you to use a particular Id in table which will make easier for jQuery to select a particular table in a page.
<table id="tblAttendance">
Upvotes: 0
Reputation:
$('table')
.on('change', ':radio', function () {
$(this).next('label').text('True').closest('td')
.siblings().find('label').text('False');
})
.find('label').filter(function(){
return $(this).text().toLowerCase() === 'true';
}).closest('td').find('input').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td> <input type='radio' name='attandance' id="opt1"><label for="opt1">False</label></td>
<td> <input type='radio' name='attandance' id="opt2"><label for="opt2">True</label></td>
<td> <input type='radio' name='attandance' id="opt3"><label for="opt3">False</label></td>
</tr>
</table>
I changed span
to label
, too, because it's a good practice. But the essence is: find the label/span, check the text, and go up a level to find and change the input
.
Upvotes: 0