我试图将输入转换为表单上的复选框。选中时,我希望值为1,未选中为零。我尝试了一些东西但是在提交时,值没有被添加到数据库中。
HTML-1:
<div class="col-sm-5 col-sm-push-1 form-group required">
<label class="control-label" for="input-active"><?php echo $entry_active; ?></label>
<div class="input-active required">
<input type="checkbox" name="active" value="0" placeholder="<?php echo $text_active; ?>" id="input-active" class="form-control" />
</div>
<?php if (isset($error_date_starting)) { ?>
<label class="text-danger"><?php echo $error_code; ?></label>
<?php } ?>
</div>ut type="checkbox" name="active" value="0" placeholder="<?php echo $text_active; ?>" id="input-active" class="form-control" />
</div>
<?php if (isset($error_date_starting)) { ?>
<label class="text-danger"><?php echo $error_code; ?></label>
<?php } ?>
</div>
HTML-2:
<div class="col-sm-5 col-sm-push-1 form-group required">
<label class="control-label" for="input-active"><?php echo $entry_active; ?></label>
<div class="input-active required">
<input type="hidden" name='active' value='0' placeholder="<?php echo $text_active; ?>" id="input-active" class="form-control" />
<input type="checkbox" name='active' value='1' placeholder="<?php echo $text_active; ?>" id="input-active" class="form-control" />
</div>
<?php if (isset($error_date_starting)) { ?>
<label class="text-danger"><?php echo $error_code; ?></label>
<?php } ?>
</div>
我尝试了一些Javascripts解决方案,但都没有效果:
<script type="text/javascript">
$('#input-active').on('change', function(){
this.value = this.checked ? 1 : 0;
// alert(this.value);
}).change();
</script>
UPDATE !! 仍然没有工作我已经改变了代码,因为建议仍然没有做我喜欢的事情。
新HTML:
<div class="col-sm-5 col-sm-push-1 form-group required">
<label class="control-label" for="input-active"><?php echo $entry_active; ?></label>
<div class="input-active required">
<input type="checkbox" name='active' value='0' placeholder="<?php echo $text_active; ?>" id="input-active" class="form-control" />
</div>
<?php if (isset($error_date_starting)) { ?>
<label class="text-danger"><?php echo $error_code; ?></label>
<?php } ?>
</div>
新JS:
<script type="text/javascript">
$("#input-active").change(function() {
if(this.checked) {
$("#input-active").val('1');
} else {
$("#input-active").val('0');
}
});
</script>
答案 0 :(得分:0)
要捕获输入类型的切换事件,请使用以下函数
$("#input-active").change(function() {
if($(this).is(':checked')) {
console.log('checked')
$(this).val(1);
} else {
console.log('un checked')
$(this).val(0);
}
console.log($(this).val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5 col-sm-push-1 form-group required">
<label class="control-label" for="input-active">In active</label>
<div class="input-active required">
<input type="checkbox" name='active' value='0' placeholder="Active" id="input-active" class="form-control" />
</div>
</div>