[英]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.