Reputation: 13
I have dynamically generated checkbox from database and output looks like
<label class="check" for="encs_1"><input data-size="33400361270" type="checkbox" name="encs[]" id="encs_1" value="1"><b></b><i>checkbox1</i></label>
<label class="check" for="encs_2"><input data-size="118062750" type="checkbox" name="encs[]" id="encs_2" value="2"><b></b><i>checkbox2</i></label>
There is anyway with jquery to automatically checked field after page loaded based on data-size so the field with the lowest value will be checked?
Upvotes: 1
Views: 458
Reputation:
You could do this using JavaScript.
Try this code:
<script>
const encs = document.querySelectorAll("input[name='encs[]']");
var i = 0;
for (i = 0; i < encs.length; i++) {
if(encs[i].dataset.size=="118062750"){
document.getElementById(encs[i].id).checked = true;
}
}
</script>
Upvotes: 1
Reputation: 31992
You can get the input with the lowest data-size
attribute by selecting all inputs, using jQuery.map
to extract the data-size
attribute, then using Math.min
.
const min = Math.min(...$('input[data-size]').map(function(){ return $(this).data('size')}))
$('input[data-size="'+min+'"]').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="check" for="encs_1"><input data-size="33400361270" type="checkbox" name="encs[]" id="encs_1" value="1"><b></b><i>checkbox1</i></label>
<label class="check" for="encs_2"><input data-size="118062750" type="checkbox" name="encs[]" id="encs_2" value="2"><b></b><i>checkbox2</i></label>
Upvotes: 0