[英]Is there a way to change the color of the selected radio button in JavaScript?
[英]Display the value of button in the text box and change the color of the selected button in javascript
我正在尝试在文本框中显示按钮值,并且我想更改所选按钮的背景颜色。 这是代码。 在文本框中显示按钮值工作正常,但如何更改所选按钮的背景颜色
<div class="input-group">
<input type="text" id="display" class="form-control" aria-label="Text input with dropdown button" >
<div class="input-group-btn">
<div class="dropdown-menu dropdown-menu-right">
<button type="button" class="dropdown-item" value="1000">1000</button>
<button type="button" class="dropdown-item" value="2000">2000</button>
<div role="separator" class="dropdown-divider"></div>
<button type="button" class="dropdown-item" value="3000">3000</button>
<div role="separator" class="dropdown-divider"></div>
<button type="button" class="dropdown-item" option value="4000">4000</button>
</div>
</div>
</div>
</div>
</div><br><br>
<input name="submit" type ="submit" value="click to submit">
<input name="reset" type ="reset" value="Reset">
</fieldset>
</form>
<script type="text/javascript">
var buttons = document.querySelectorAll('.dropdown-item')
var textbox = document.getElementById('display')
for (let i=0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function(e) {
textbox.value = e.target.value
})
}
</script>
您可以使用 CSS class 突出显示活动按钮。 您可以在事件处理程序中使用this
关键字引用单击的按钮以添加 class。 要从所有按钮中删除 class,您可以使用buttons
集合。
如果你把后面的逻辑放到它自己的function中,那么你也可以在表单的reset
事件上调用它。
尝试这个:
let form = document.querySelector('#yourForm'); let buttons = document.querySelectorAll('.dropdown-item'); let textbox = document.getElementById('display'); let setAllButtonsInactive = () => buttons.forEach(btn => btn.classList.remove('active')); buttons.forEach(btn => { btn.addEventListener("click", function(e) { textbox.value = e.target.value; setAllButtonsInactive(); this.classList.add('active'); }) }); form.addEventListener('reset', setAllButtonsInactive);
button.active { background-color: #C00; color: #FFF; }
<form id="yourForm"> <fieldset> <div> <div> <div class="input-group"> <input type="text" id="display" class="form-control" aria-label="Text input with dropdown button"> <div class="input-group-btn"> <div class="dropdown-menu dropdown-menu-right"> <button type="button" class="dropdown-item" value="1000">1000</button> <button type="button" class="dropdown-item" value="2000">2000</button> <div role="separator" class="dropdown-divider"></div> <button type="button" class="dropdown-item" value="3000">3000</button> <div role="separator" class="dropdown-divider"></div> <button type="button" class="dropdown-item" option value="4000">4000</button> </div> </div> </div> </div> </div><br><br> <input name="submit" type="submit" value="click to submit"> <input name="reset" type="reset" value="Reset"> </fieldset> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.