我正在尝试使用JavaScript选中复选框时自动填充我的文本区域。
这是我目前的观点:
.section
.section_header Advanced Settings
.panel.panel-primary
.panel-body
.form-group
= f.check_box :hello, { label: "hello", checked: @user.hello }, '1', '0'
= f.text_field :tag, value: @tag
如果选中此复选框,我希望文本字段包含“ hello”,否则,请保留为空白。
我该怎么做?
您可以添加内联JavaScript这样的内容,但您可能希望将其提取到单独的文件中:
.section
.section_header Advanced Settings
.panel.panel-primary
.panel-body
.form-group
= f.check_box :hello, { id: 'hello_cb', label: "hello", checked: @user.hello }, '1', '0'
= f.text_field :tag, value: @tag, id: 'tag_field'
:javascript
let checkbox = document.getElementById('hello_cb')
let input = document.getElementById('tag_field')
checkbox.onchange = function() {
input.value = checkbox.checked ? 'hello' : ''
}
我还将ID添加到元素中以便于定位,但您可以在不触摸原始HTML的情况下以不同的方式定位它们。
使用jQuery:
(考虑您的复选框ID为hello
,而您的text_field ID为tag
)
$(document).ready(function(){
$('#hello').change(function(){
if(this.checked){
$('#tag').val('hello');
} else {
$('#tag').val('');
}
});
});