如果未选中复选框,则禁用引导输入按钮

Disable bootstrap input button if checkbox not checked

本文关键字:输入 按钮 复选框 如果      更新时间:2023-09-26

我的复选框在取消选中我的输入时应该被禁用,id为删除,但由于某种原因,java脚本代码它没有同时拾取输入和选中输入的id。我使用引导程序 3 和代码点火器。

我的代码有什么问题?不知道为什么不工作。所有 JS 脚本加载正确。

<script type="text/javascript">
$('#check_delete').click(function(){
    if($(this).attr('checked') == false){
         $('input #delete').attr("disabled","disabled");   
    } else {
        $('input #delete').removeAttr('disabled');
    }
});
</script>
<input type="submit" role="button" class="btn btn-danger" id="delete" value="Delete">

视图

<?php echo form_open('admin/users_group/delete');?>
<div class="table-responsive">
<table  class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td style="width: 1px;" class="text-center"><input type="checkbox" onclick="$('input[name*=''selected'']').prop('checked', this.checked);" /></td>
<th class="text-left">User Group ID</th>
<th class="text-left">Name</th>
<th class="text-right">Action</th>
</tr>
</thead>
<?php if ($users_group == TRUE) {?>
<?php foreach ($users_group as $user_group) { ?>
    <tr>
    <td class="text-center"><?php if (in_array($user_group['user_group_id'], $selected)) { ?>
    <input type="checkbox" id="check_delete" name="selected[]" value="<?php echo $user_group['user_group_id']; ?>" checked="checked" />
    <?php } else { ?>
    <input type="checkbox" id="check_delete" name="selected[]" value="<?php echo $user_group['user_group_id']; ?>" />
    <?php } ?>
    </td>
    <td class="text-left"><?php echo $user_group['user_group_id']; ?></td>
    <td class="text-left"><?php echo $user_group['name']; ?></td>
    <td class="text-right">
    <input type="submit" role="button" class="btn btn-danger" id="delete" value="Delete">
    <a href="<?php echo $user_group['edit']; ?>" class="btn btn-primary"><i class="fa fa-pencil"></i> Edit</a></td>
    </tr>
<?php } ?>
<?php } else { ?>
<tr>
 <td class="text-center" colspan="3">No Results</td>
</tr>
<?php } ?>
</table>
</div>
<?php echo form_close();?>
</div>
<div class="panel-footer clearfix">
<div class="pull-left pag-user-group"><?php echo $pagination; ?></div>
<div class="pull-right" style="padding-top: 7.5px;"><?php echo $results; ?></div>
</div>
</div>
</div>
</div>
</div><!-- # Page Inner End -->
</div><!-- # Page End -->
</div><!-- # Wrapper End -->
<script type="text/javascript">
$('#check_delete').click(function(){
    if($(this).attr('checked') == false){
         $('input #delete').attr("disabled","disabled");   
    } else {
        $('input #delete').removeAttr('disabled');
    }
});
</script>

在 HTML 代码之前声明脚本。

按顺序读取 HTML 页面。

alert( $('input#delete').length )
<input id="delete" >

这将提醒"0",因为 jQuery 会查找 #delete,然后下一行 #delete 存在。

两种解决方案:

1) 将脚本移动到 HTML 之后,末尾,在 </body> 标记之前。

2) 将您的代码包装在 $(function(){ /* Your code here */ } 中。这将等待页面准备就绪,然后再执行脚本。

<input id="delete" >
alert( $('input#delete').length )

这将起作用,这也将:

$(function(){
   alert( $('input#delete').length )
})
<input id="delete" >