【问题标题】:changing span value when checkbox is checked and unchecked选中和取消选中复选框时更改跨度值
【发布时间】:2019-10-30 15:43:45
【问题描述】:
我希望在选中复选框时更改跨度值,然后在未选中时更改回原始值。
<span id="shipping">Standard</span>
<input class="form-check-input" type="checkbox" name="ship" value="Expedited" id="exp1">
原始值为“标准”。我想在选中时将其更改为“加急”,如果未选中,我想将其更改为“标准”。我该怎么做?
【问题讨论】:
标签:
javascript
html
checkbox
【解决方案1】:
试试这样。将 eventListener 添加到该复选框并检查状态并更改其值。
document.getElementById('exp1').addEventListener('click', function(){
if(this.checked){
this.value = 'Expedited';;
document.getElementById('name').innerHTML = 'Expedited';
}
else{
this.value = 'Standard';
document.getElementById('name').innerHTML = 'Standard';
}
});
<input class="form-check-input" type="checkbox" name="ship" value="Standard" id="exp1"><span id="name">Standard<span>
【解决方案2】:
您可以使用Standard & Expedited 和一个类hiddden 创建两个文本子span。然后在更改复选框时获取所有子跨度文本并使用 toggle 添加或删除 hidden 类
document.getElementById('exp1').addEventListener('change', function(e) {
changeDisplay()
})
function changeDisplay() {
document.querySelectorAll('.spanTxt').forEach(function(elem) {
elem.classList.toggle('hidden')
})
}
.hidden {
display: none;
}
<span>
<span class="spanTxt">Standard</span>
<span class="spanTxt hidden">Expedited</span>
</span>
<input class="form-check-input" type="checkbox" name="ship" value="Expedited" id="exp1">