我有一个文本字段,其中包含从数据库填充的图像值。我需要有一个复选框,可以在选中时清除值,并在未选中时恢复值。如果复选框被选中,文本输入的清除值如果使用javascript未选中,恢复值
<input type="text" value="/images/sampleimage.jpg" />
Remove this image <input type="checkbox" name="remove">
我有一个文本字段,其中包含从数据库填充的图像值。我需要有一个复选框,可以在选中时清除值,并在未选中时恢复值。如果复选框被选中,文本输入的清除值如果使用javascript未选中,恢复值
<input type="text" value="/images/sampleimage.jpg" />
Remove this image <input type="checkbox" name="remove">
更改HTML到:
<input type="text" value="/images/sampleimage.jpg" class="remove"/>
Remove this image <input type="checkbox" name="remove" class="handler">
和JS: 与jquery
$('.handler').click(function() {
$('.remove').val("Replace by new value");
});
IE7不会喜欢这一点,是它与jQuery的方式更容易。
<input id="A" type="text" value="/images/sampleimage.jpg" />
Remove this image <input id="CHA" onclick="swapOut(this,'A')" type="checkbox" name="remove">
JS:
function swapOut(element,id) {
target = document.getElementById(id)
if(element.checked) {
element.setAttribute('rel',target.value)
target.value=''
}
else {
target.value = element.getAttribute('rel')
}
}
assumming您的复选框有#检查的ID,和你输入具有#INPUT的输入,
$('#check').change(function(){
if($(this).is(':checked')){
$('#input').val(,$('#input').data('previous_value'));
} else {
$('#input').data('previous_value',$('#input').val());
}
};
这将添加一个名为属性“ data-previous_value“添加到您的输入中,该选项保留未选中复选框时的值,并在检查时将其检索到输入值中。
哦,这是jQuery,不是纯javascript。 – Andri
这里是一个JavaScript的解决方案(不需要jQuery的)
HTML:
<input id="imgInput" type="text" value="/images/sampleimage.jpg" />
Remove this image <input type="checkbox" id="remove" name="remove">
JS:
var imgInput = document.getElementById('imgInput'),
remove = document.getElementById('remove'),
val = imgInput.value;
remove.onchange = function() {
if (this.checked) {
imgInput.value = "";
} else {
imgInput.value = val;
}
}
注意'.toggle'切换知名度,没有价值。 – pimvdb
哦,我提出了他的问题。错误。虐待编辑它。 – kritya