jarij98
jarij98

Reputation: 13

Auto checkbox checked on page load based on value

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

Answers (2)

user16749811
user16749811

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

Spectric
Spectric

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

Related Questions