在我的页面上更改复选框后运行函数

Run function after a checkbox change on my page

本文关键字:复选框 运行 函数 我的      更新时间:2023-09-26

我在页面上动态创建了复选框,并为每个复选框分配了一个唯一的id,如"renametam1'"、"renametem2'"等。当其中一个复选框被选中时,我正试图运行一个函数。然后,该函数将允许用户输入以前只读的相应字段。

我试过以下方法,但似乎不起作用。

var a=0;
$('input[type=checkbox]').change(function () {
for (var i=0;i<rows3;i++){
     a=a+1;
     var id= '#renameteam'+a;
if ($(id).is(":checked")) {
    $('#newname'+a).removeProp('readonly');
  }
 }
//Here do the stuff you want to do when 'unchecked'
});

有什么建议吗?

就是这样做的

//delegate the event so you can call this on document ready and it will still be bound to any dynamically created elements
$(document).on('change', 'input[type=checkbox]', function() {
  var checkbox = $(this),
    otherInput = $('#' + checkbox.data('id'));
  otherInput.prop('readonly', !checkbox.is(':checked'));
  if (!checkbox.is(':checked')) {
      // do stuff here when checkbox isn't checked - not sure if you still want this bit but it is as per your comments in the code above
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="" id="renameteam1" data-id="newname1" />
<!-- use a data attribute to target the id of the input you want to make readonly -->
<input type="textbox" name="textbox" value="" id="newname1" readonly />

如果你不想使用数据属性,你可以这样做:

//delegate the event so you can call this on document ready and it will still be bound to any dynamically created elements
$(document).on('change', 'input[type=checkbox]', function() {
  var checkbox = $(this),
    otherInput = $('#newname' + this.id.replace('renameteam', ''));
  otherInput.prop('readonly', !checkbox.is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="" id="renameteam1" />
<!-- use a data attribute to target the id of the input you want to make readonly -->
<input type="textbox" name="textbox" value="" id="newname1" readonly />

尝试对复选框和单选按钮使用点击而不是更改。