Xibition Xibition - 4 months ago 17
Javascript Question

change checkbox label after select

I have some checkboxes (101) which labels should change based on a select input. The JS I have only runs for one, which is logical. Though I'm not very familiar with jquery functions, I don't know how to proceed for all the 101 checkboxes.

the inputs :

<?php

for ($i = 1; $i < 102; $i++): //adjust this number to whatever number of checkboxes you want
echo '<div class="each_checkboxes">';
// $j = sprintf('%04u', $i);

echo '<label id="contact" for="checkbox"></label>';
echo '<input type="checkbox" name="tape[]" id="checkbox" value=""/>';

echo '</div>';

endfor;
?>


the select :

<select id="method" name="server" class="custom-dropdown__select custom-dropdown__select--white" required>
<option value="0" default>
Choose server
</option>
<option value="server1">server 1</option>
<option value="server2">server 2</option>
</select>


the js :

$(document).ready(function () {
$('#method').change(
function () {
var method = $('option:selected').val();

if (method == "server1") {

$('#contact').text("MA" + i);

} else if (method == "server2") {

$('#contact').text("SAS" + i);

}
});

});

Answer

You need to use class instead of id, because id should be unique for each element. Try like following.

PHP:

<?php
    for ($i = 1; $i < 102; $i++): 

        echo '<div class="each_checkboxes">';

        echo '<label class="contact" for="checkbox'.$i.'"></label>';
        echo '<input type="checkbox" name="tape[]" id="checkbox'.$i.'" value=""/>';

        echo '</div>';

    endfor;
?>

jQuery:

$(document).ready(function () {
    $('#method').change(function () {
        var method = $('option:selected').val(),
            text = "";

        if (method == "server1") {
            text = "MA";
        } else if (method == "server2") {
            text = "SAS";
        }

        $('.contact').each(function(i) {
            $(this).text(text + (++i));
        });
    });
});