我不知道如何正确引用我的代码来禁用带有复选框的文本。
<form method='POST'>
<?php
$index = 0 ;
while($index <= 4){
echo "<input class='click' type='text' data-text='test$index' id='text$index' value='text$index' disabled>test$index</input><br>";
echo "<input type='checkbox' id='test$index' >test$index</input><br><br>";
$index++;
}
?>
</form>
上面我有一个循环的复选框和文本框
下面是我的 jQuery 代码
$(document).ready(function() {
var id = $(this).attr('id');
$('#'+id).change(function(){
var disable = $(this).attr('data-text');
if(('#'+disable).prop('checked')){
$('#'+disable).removeAttr('disabled');
}
else{
$('#'+disable).attr('disabled');
}
});
});
下面是通过堆栈片段的现场演示
$(document).ready(function() {
$('.click').change(function() {
var disable = $(this).attr('data-text');
if (('#' + disable).prop('checked')) {
$('#' + disable).prop('disabled', false);
} else {
$('#' + disable).prop('disabled', true);
}
});
});
<form method='POST'>
<input class='click' type='text' data-text='test0' id='text0' value='text0' disabled>test0</input>
<br>
<input type='checkbox' id='test0'>test0</input>
<br>
<br>
<input class='click' type='text' data-text='test1' id='text1' value='text1' disabled>test1</input>
<br>
<input type='checkbox' id='test1'>test1</input>
<br>
<br>
<input class='click' type='text' data-text='test2' id='text2' value='text2' disabled>test2</input>
<br>
<input type='checkbox' id='test2'>test2</input>
<br>
<br>
<input class='click' type='text' data-text='test3' id='text3' value='text3' disabled>test3</input>
<br>
<input type='checkbox' id='test3'>test3</input>
<br>
<br>
<input class='click' type='text' data-text='test4' id='text4' value='text4' disabled>test4</input>
<br>
<input type='checkbox' id='test4'>test4</input>
<br>
<br>
</form>
最佳答案
试试这个:我希望我已经解决了你的问题,这里是完整的代码
</html>
<form method='POST'>
<?php
$index = 0 ;
while($index <= 4){
echo "<input type='text' id='text$index' value='text$index' >test$index</input><br>";
echo "<input class='click' id='test$index' data-text='$index' type='checkbox' >test$index</input><br><br>";
$index++;
}
?>
</form>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.click').click(function(){
var disable = $(this).attr('data-text');
if ("#"+disable.change ){
$("#text"+disable).attr("disabled", $(this).is(':checked'));
}
});
});
</script>
关于javascript - 如何禁用循环内的文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34772941/