I'm trying to refactor a small Javascript function that simply adds an active class to the parent <div> of a series of radio buttons on page load as well as via a change.
My function is:
function toggleActiveState (event) {
const el = event.target
const parent = el.closest('[data-toggle-has-btn-group]')
const buttons = parent.getElementsByClassName('js__btn-toggle')
var i
for (i = 0; i < buttons.length; i++) {
buttons[i].classList.remove('active')
}
el.parentElement.classList.add('active')
}
My markup is:
<div class="form-group">
<div class="btn-group-toggle d-flex flex-row" data-toggle="buttons" data-toggle-has-btn-group>
<label class="btn btn-custom btn-outline-primary btn-sm active flex-fill mr-1 js__btn-toggle">
<input type="radio" name="options" id="option1" value="Mr" checked onclick="toggleActiveState(event)"> Mr
</label>
<label class="btn btn-custom btn-outline-primary btn-sm flex-fill mx-1 js__btn-toggle">
<input type="radio" name="options" id="option2" value="Mrs" onclick="toggleActiveState(event)"> Mrs
</label>
<label class="btn btn-custom btn-outline-primary btn-sm flex-fill mx-1 js__btn-toggle">
<input type="radio" name="options" id="option3" value="Miss" onclick="toggleActiveState(event)"> Miss
</label>
<label class="btn btn-custom btn-outline-primary btn-sm flex-fill ml-1 js__btn-toggle">
<input type="radio" name="options" id="option4" value="Other" onclick="toggleActiveState(event)"> Other
</label>
</div>
</div>
When clicking a radio button, the toggleActiveState(event) runs and I'm able to remove the active classes and add a class to the input I clicked.
I have multiple of these .btn-group-toggle elements on the page.
What I need to do is be able to set the active class state of say the Mrs element on page load and it's value by calling my function like so:
toggleActiveState('options', 'Mrs') and then this would be active, and selected...
Any ideas?
You can add event listener on window load and add the class there. Like I've done below based on your code.
function toggleActiveState (event) {
const el = event.target
const parent = el.closest('[data-toggle-has-btn-group]')
const buttons = parent.getElementsByClassName('js__btn-toggle')
var i
for (i = 0; i < buttons.length; i++) {
buttons[i].classList.remove('active')
}
el.parentElement.classList.add('active')
}
window.addEventListener('load', () => {
const checkedInput = document.querySelector('input[type="radio"]:checked');
checkedInput.parentElement.classList.add('active');
})
.active {
color: red;
}
<div class="form-group">
<div class="btn-group-toggle d-flex flex-row" data-toggle="buttons" data-toggle-has-btn-group>
<label class="btn btn-custom btn-outline-primary btn-sm flex-fill mr-1 js__btn-toggle">
<input type="radio" name="options" id="option1" value="Mr" checked onclick="toggleActiveState(event)"> Mr
</label>
<label class="btn btn-custom btn-outline-primary btn-sm flex-fill mx-1 js__btn-toggle">
<input type="radio" name="options" id="option2" value="Mrs" onclick="toggleActiveState(event)"> Mrs
</label>
<label class="btn btn-custom btn-outline-primary btn-sm flex-fill mx-1 js__btn-toggle">
<input type="radio" name="options" id="option3" value="Miss" onclick="toggleActiveState(event)"> Miss
</label>
<label class="btn btn-custom btn-outline-primary btn-sm flex-fill ml-1 js__btn-toggle">
<input type="radio" name="options" id="option4" value="Other" onclick="toggleActiveState(event)"> Other
</label>
</div>
</div>
Related
We have three buttons(English, Hindi & Urdu). How I can get the value of Selected button in JavaScript function?
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" checked> English
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2"> Hindi
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3"> Urdu
</label>
</div>
Firstly set value to your radio buttons then get buttons and bind event listener.
and you can get value of button from event target as following:
let btns= document.getElementsByName("options");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click",function(e) {
console.log(e.target.value);
});
}
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" checked value="English">English
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2"value="Hindi">Hindi
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" value="Urdu">Urdu
</label>
</div>
Try This:
https://jsfiddle.net/f7ed1o0n/
$('input[name="options"]').change(function(){
alert($(this).val());
$(this).parents('.btn-group').find('input[type="radio"]').attr('disabled',
'disabled');
});
I have the following html displaying a scale 1-5, I get the value that is clicked but it seems as it does not toggle or change the color when a number is clicked it only changes the color temporarily as shown in file attached
<div class="row">
<div class="btn-toolbar mr-2" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group" role="group" aria-label="likert group">
<div class="btn-group btn-group-toggle mr-2" data-toggle="buttons">
<a class="btn btn-link disabled ml-5" disabled>Totally Not</a>
<label class="btn btn-success" >
<input type="radio" name="likert" value="1" autocomplete="off">1
</label>
<label class="btn btn-success ">
<input type="radio" name="likert" value="2" autocomplete="off">2
</label>
<label class="btn btn-success ">
<input type="radio" name="likert" value="3" autocomplete="off">3
</label>
<label class="btn btn-success ">
<input type="radio" name="likert" value="4" autocomplete="off">4
</label>
<label class="btn btn-success ">
<input type="radio" name="likert" value="5" autocomplete="off">5
</label>
<a class="btn btn-link disabled" disabled>Very Much</a>
</div>
</div>
</div>
</div>
How can I make it maintain the toggle effect once it is selected?Is there something missing from the above code ?
(I use Meteor Blaze framework with Bootstrap 4)
The solution was to add the below javascript file of npm module in meteor js file
import 'bootstrap/dist/js/bootstrap.bundle'
Consider we create radio buttons dynamically, so we can't access them by Id
<label class="btn btn-sm btn-white" onclick="test();"> <input type="radio" value="abc" name="options"> this is a text </label>
<label class="btn btn-sm btn-white" onclick="test();"> <input type="radio" value="dfdf" name="options"> this is a text </label>
<label class="btn btn-sm btn-white" onclick="test();"> <input type="radio" value="reewr" name="options"> this is a text </label>
How can alert the value of radiobutton inside clicked label?
function test(event){
event.stopPropagation();
console.log(event.currentTarget.firstElementChild.value);
}
<label class="btn btn-sm btn-white" onclick="test(event);"> <input type="radio" value="abc" name="options"> this is a text </label>
<label class="btn btn-sm btn-white" onclick="test(event);"> <input type="radio" value="dfdf" name="options"> this is a text </label>
<label class="btn btn-sm btn-white" onclick="test(event);"> <input type="radio" value="reewr" name="options"> this is a text </label>
First of all, you shouldn't really be using inline JS binding: use addEventListener instead. In the callback triggered by addEventListener, you will be able to get a reference to the element that triggers it via event.target.
event.target may refer to the <label> element or the <input> element, so we just have a simple if/else check to see which element the event is fired from, by checking event.target.tagName. If is an <input> element, we just get the element's value property.
See proof-of-concept below:
// Select the label elements in your DOM
// Note: You might have to adjust this!
var labelEls = document.querySelectorAll('label');
// Iterate through all selected `<label>` elements
Array.prototype.slice.call(labelEls).forEach(function(labelEl) {
// Iteratively add the `click` event listener
labelEl.addEventListener('click', function(event) {
// If event is emitted by `<input>`
if (event.target.tagName === 'INPUT') {
console.log('Value: ' + event.target.value);
}
});
});
<label class="btn btn-sm btn-white"> <input type="radio" value="abc" name="options"> this is a text </label>
<label class="btn btn-sm btn-white"> <input type="radio" value="dfdf" name="options"> this is a text </label>
<label class="btn btn-sm btn-white"> <input type="radio" value="reewr" name="options"> this is a text </label>
You can use label.control to reference HTML element associated with the label. Also avoid writing inline event handlers.
document.querySelectorAll("label").forEach(e => {
e.addEventListener("click", function(event){
// this will refer to label
console.log(this.control.value);
})
});
<label class="btn btn-sm btn-white"> <input type="radio" value="abc" name="options"> this is a text </label>
<label class="btn btn-sm btn-white"> <input type="radio" value="dfdf" name="options"> this is a text </label>
<label class="btn btn-sm btn-white"> <input type="radio" value="reewr" name="options"> this is a text </label>
Try like this:
html
onclick=“test(this)”
js
function test(elmnt) {
alert(elmnt.childNodes[1].value)
}
It's always better to add classes to a set of labels that you want to attach event listeners rather than attaching listeners based on tag names as there could many labels on your site webpage.
I have devised a solution using vanilla JS. Checks are done for event propagation (bubbling and capturing), type of the child element and tag name of the child element. This would keep the code safe even if we you add additional child elements to these labels when your application expands.
var labels = document.getElementsByClassName('labels');
for (var i = 0; i < labels.length; ++i) {
labels[i].addEventListener('click', function(event) {
if (event.target.tagName === 'LABEL') {
var kids = this.children;
for (var j = 0; j < kids.length; ++j) {
if (kids[j].type === 'radio' && kids[j].nodeName === 'INPUT') {
console.log(kids[j].value);
}
}
}
});
}
<label class="btn btn-sm btn-white labels"> <input type="radio" value="abc" name="options"> this is a text </label>
<label class="btn btn-sm btn-white labels"> <input type="radio" value="dfdf" name="options"> this is a text </label>
<label class="btn btn-sm btn-white labels"> <input type="radio" value="reewr" name="options"> this is a text </label>
Identify each input with an id, then pass it to each test():
<script type="text/javascript">
function test(e, id) {
var el = document.getElementById(id);
console.log(el.value);
}
</script>
<label class="btn btn-sm btn-white"> <input onclick="test(event,'id1')" type="radio" id="id1" value="abc" name="options"> this is a text </label>
<label class="btn btn-sm btn-white"> <input onclick="test(event,'id2');" type="radio" id="id2" value="dfdf" name="options"> this is a text </label>
<label class="btn btn-sm btn-white"> <input onclick="test(event,'id3');" type="radio" id="id3" value="reewr" name="options"> this is a text </label>
I am kinda new to javascript and I checked lessons on w3 about javascript but i did not get my answer so far.
I have a question and 4 options and I want to change the color of label.btn that clicked on.
javascript:
$(function(){
$("label.btn").on('click',function () {
var choice = $(this).find('input:radio').val();
$( "#answer" ).html( $(this).checking(choice) );
ClickedLabel.style.backgroundColor = "black"; // I want to change te color here
});
///
};
html:
<div class="modal-body">
<div class="quiz" id="quiz" data-toggle="buttons">
<label id="first" class="element-animation1 btn btn-lg btn-primary btn-block"><span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span> <input type="radio" name="q_answer" value="1">1 One</label>
<label id="second" class="element-animation2 btn btn-lg btn-primary btn-block"><span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span> <input type="radio" name="q_answer" value="2">2 Two</label>
<label id="third" class="element-animation3 btn btn-lg btn-primary btn-block"><span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span> <input type="radio" name="q_answer" value="3">3 Three</label>
<label id="fourth" class="element-animation4 btn btn-lg btn-primary btn-block"><span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span> <input type="radio" name="q_answer" value="4">4 Four</label>
</div>
</div>
Any help would be appreciated, Thanks!
A)
Run my code and switch between the options.
$(function(){
$("label.btn").on('click',function () {
$("label.btn").css('background-color','transparent');
$(this).css('background-color','red');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<div class="quiz" id="quiz" data-toggle="buttons">
<label id="first" class="element-animation1 btn btn-lg btn-primary btn-block">
<span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span>
<input type="radio" name="q_answer" value="1">1 One</label>
<label id="second" class="element-animation2 btn btn-lg btn-primary btn-block">
<span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span>
<input type="radio" name="q_answer" value="2">2 Two</label>
<label id="third" class="element-animation3 btn btn-lg btn-primary btn-block">
<span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span>
<input type="radio" name="q_answer" value="3">3 Three</label>
<label id="fourth" class="element-animation4 btn btn-lg btn-primary btn-block">
<span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span>
<input type="radio" name="q_answer" value="4">4 Four</label>
</div>
</div>
OR
In this example I used the closest method to find the wrapper label of the clicked radio button and used .css('background-color','red') to change its color. Also I wrote $("label.btn").css('background-color','transparent'); to reset the color of all options to transparent in each click first.
$(function(){
$("input").on('click',function () {
$("label.btn").css('background-color','transparent');
$(this).closest("label").css('background-color','red');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<div class="quiz" id="quiz" data-toggle="buttons">
<label id="first" class="element-animation1 btn btn-lg btn-primary btn-block">
<span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span>
<input type="radio" name="q_answer" value="1">1 One</label>
<label id="second" class="element-animation2 btn btn-lg btn-primary btn-block">
<span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span>
<input type="radio" name="q_answer" value="2">2 Two</label>
<label id="third" class="element-animation3 btn btn-lg btn-primary btn-block">
<span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span>
<input type="radio" name="q_answer" value="3">3 Three</label>
<label id="fourth" class="element-animation4 btn btn-lg btn-primary btn-block">
<span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span>
<input type="radio" name="q_answer" value="4">4 Four</label>
</div>
</div>
B)
Another way is to toggle a active class on the clicked item. I have been written an example based on this way HERE. Toggle a class is a nice way ;)
$(this) will be the label that was clicked. You can use jquery to change the background color through .css
Instead of
ClickedLabel.style.backgroundColor = "black";
you can use
$(this).css('background-color', 'black');
If you would rather use style.backgroundColor you can get the base element and modify that:
$(this)[0].style.backgroundColor = "black";
$(this).css("background-color","black");
I am using knockout binding for radio button with bootstrap.
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input class="radio-inline" type="radio" data-bind="checked:daysBackParameter" value="true" name="daysradio" >{{texts.showAll}}
</label>
<label class="btn btn-default">
<input class="radio-inline" type="radio" data-bind="checked:daysBackParameter" value="30" name="daysradio" >{{texts.showOnly30Days}}
</label>
<label class="btn btn-default">
<input class="radio-inline" type="radio" data-bind="checked:daysBackParameter" value="60" name="daysradio" >{{texts.showOnly60Days}}
</label>
<label class="btn btn-default">
<input class="radio-inline" type="radio" data-bind="checked:daysBackParameter" value="90" name="daysradio" >{{texts.showOnly90Days}}
</label>
<!--
<label class="btn btn-default">
<span style="cursor:pointer" data-bind="click: function(){ filterClick(30) } ,css: { 'selectedFilter' : filterValue == 30 }"><u>30 </u></span>
</label>
-->
</div>
the probelm is when i use data-toggle=buttons then data-bind is not working
but if i remove this then data-binding works.
but in that case radio button style comes but i need button styles.
Could you please suggest any solution?
I used the mentioned custom binding and it worked for me. The deatails custom binding will be found on this custom biding by Roy J
<div class="btn-group" data-bind="radio: userType">
<button type="button" class="btn btn-primary" data-value="company">Main User</button>
<button type="button" class="btn btn-primary" data-value="person">Dummy user</button>