我有一些复选框 (101),其标签应根据选择输入进行更改。我的JS只运行一个,这是合乎逻辑的。虽然我对 jquery 函数不是很熟悉,但我不知道如何处理所有 101 个复选框。
输入:
<?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;
?>
选择:
<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>
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);
}
});
});
最佳答案
您需要使用class
而不是id
,因为id
对于每个元素应该是唯一的。尝试如下。
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) {
var value = text + (++i);
$(this).text(value);
$('#' + $(this).attr('for')).val(value);
});
});
});
关于javascript - 选择后更改复选框标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38784798/