Make a checkbox / radio label bold on check with JavaScript - javascript

I want to make the parent label element bold on a radio / checkbox check. It's working for checkboxes, but the radio's label stays bold.
HTML:
<h4>Radios:</h4>
<div class="checkgroup">
<label for="green"><input type="radio" name="test" id="green">Green</label>
<label for="blue"><input type="radio" name="test" id="blue">Blue</label>
<label for="red"><input type="radio" name="test" id="red">Red</label>
</div>
<hr />
<h4>Checkboxes:</h4>
<div class="checkgroup">
<label for="green-check"><input type="checkbox" id="green-check">Green</label>
<label for="blue-check"><input type="checkbox" id="blue-check">Blue</label>
<label for="red-check"><input type="checkbox" id="red-check">Red</label>
</div>
JavaScript:
function makeLabelBold() {
const radios = document.querySelectorAll("input[type='radio']");
const checkboxes = document.querySelectorAll("input[type='checkbox']");
radios.forEach((radio) => {
radio.addEventListener("click", function () {
this.checked
? (this.parentElement.style.fontWeight = "700")
: (this.parentElement.style.fontWeight = "400");
});
});
checkboxes.forEach((checkbox) => {
checkbox.addEventListener("click", function () {
this.checked
? (this.parentElement.style.fontWeight = "700")
: (this.parentElement.style.fontWeight = "400");
});
});
}
makeLabelBold();
I tried using a change event instead of a click, but that didn't work. Any ideas? Here's a Pen to try out.
Codepen:
Codepen for testing

You can do this without JavaScript. You can use :checked CSS selector. Something like this:
input:checked + span {
font-weight: 700;
}
<h4>Radios:</h4>
<div class="checkgroup">
<label for="green"><input type="radio" name="test" id="green"><span>Green</span></label>
<label for="blue"><input type="radio" name="test" id="blue"><span>Blue</span></label>
<label for="red"><input type="radio" name="test" id="red"><span>Red</span></label>
</div>
<hr />
<h4>Checkboxes:</h4>
<div class="checkgroup">
<label for="green-check"><input type="checkbox" id="green-check"><span>Green</span></label>
<label for="blue-check"><input type="checkbox" id="blue-check"><span>Blue</span></label>
<label for="red-check"><input type="checkbox" id="red-check"><span>Red</span></label>
</div>
If you would like to use JavaScript anyway:
Radio lists doesn't fire event for each of its radio box but only for the one which has been really changed (which you have clicked / as long as we are not changing its value programmaticaly). What I did:
replaced this with e.target to get radio which you have clicked.
get it's name attribute with getAttribute("name")
find all radios with same name attribute`
remove style from all radios with this attribute
apply style on currently selected radio
function makeLabelBold() {
const radios = document.querySelectorAll("input[type='radio']");
const checkboxes = document.querySelectorAll("input[type='checkbox']");
radios.forEach((radio) => {
radio.addEventListener("click", function (e) {
const inputsName = e.target.getAttribute("name");
const sameNameRadios = document.querySelectorAll("[name='"+inputsName+"']");
sameNameRadios.forEach(radio=>{
radio.parentElement.style.fontWeight = "400";
});
e.target.parentElement.style.fontWeight = "700";
});
});
checkboxes.forEach((checkbox) => {
checkbox.addEventListener("click", function () {
this.checked
? (this.parentElement.style.fontWeight = "700")
: (this.parentElement.style.fontWeight = "400");
});
});
}
makeLabelBold();
<h4>Radios:</h4>
<div class="checkgroup">
<label for="green"><input type="radio" name="test" id="green">Green</label>
<label for="blue"><input type="radio" name="test" id="blue">Blue</label>
<label for="red"><input type="radio" name="test" id="red">Red</label>
</div>
<hr />
<h4>Checkboxes:</h4>
<div class="checkgroup">
<label for="green-check"><input type="checkbox" id="green-check">Green</label>
<label for="blue-check"><input type="checkbox" id="blue-check">Blue</label>
<label for="red-check"><input type="checkbox" id="red-check">Red</label>
</div>

Without changing the HTML:
(function()
{
const
radios = document.querySelectorAll('input[type="radio"]')
, checkboxes = document.querySelectorAll('input[type="checkbox"]')
;
radios.forEach(radio =>
{
radio.onclick = () =>
radios.forEach( r =>
r.closest('label').style.fontWeight = r.checked ? '700' : '400' )
});
checkboxes.forEach(checkbox =>
{
checkbox.onclick = () =>
checkbox.closest('label').style.fontWeight = checkbox.checked ? '700' : '400'
});
}
)()
<h4>Radios:</h4>
<div class="checkgroup">
<label for="green"><input type="radio" name="test" id="green">Green</label>
<label for="blue"><input type="radio" name="test" id="blue">Blue</label>
<label for="red"><input type="radio" name="test" id="red">Red</label>
</div>
<hr />
<h4>Checkboxes:</h4>
<div class="checkgroup">
<label for="green-check"> <input type="checkbox" id="green-check">Green</label>
<label for="blue-check"> <input type="checkbox" id="blue-check" >Blue </label>
<label for="red-check"> <input type="checkbox" id="red-check" >Red </label>
</div>
you can olso do:
(function()
{
const radios_checkboxes = document.querySelectorAll('input[type="radio"], input[type="checkbox"]');
radios_checkboxes.forEach(rc =>
{
rc.onclick =()=>
radios_checkboxes.forEach(elm =>
elm.closest('label').style.fontWeight = elm.checked ? '700' : '400' )
});
}
)();

Related

How capture the input radio value in javascript?

For example I have the next options in html, define the global name and different id to each input radio:
<form id="mokepon-form">
<input type="radio" name="mokepon" id="hipodoge">
<label for="hipodoge">Hipodoge</label>
<input type="radio" name="mokepon" id="capipego">
<label for="capipego">Capipego</label>
<input type="radio" name="mokepon" id="ratigueya">
<label for="ratigueya">Ratigueya</label>
<button type="submit">Seleccionar</button>
</form>
To read the value I read the selector, the global name and the checked attribute and then read the id property, you can use the value property as well.
const chooseMokepon = (e) => {
e.preventDefault();
const $selectedMokepon = document.querySelector('input[name=mokepon]:checked');
const { id: mokeponValue } = $selectedMokepon;
if (!mokeponValue) return;
console.log(mokeponValue);
}
$mokeponForm.addEventListener('submit', e => chooseMokepon(e));
You might use this snippet:
let submitBtn = document.querySelector('button[type="submit"]');
submitBtn.addEventListener('click', function(event){
event.preventDefault();
let selectedOption = document.querySelector('input[type="radio"][name="mokepon"]:checked');
if(selectedOption && selectedOption.value){
console.log('Selected: ' + selectedOption.value);
}
});
<form id="mokepon-form">
<input type="radio" name="mokepon" id="hipodoge" value="hipodoge">
<label for="hipodoge">Hipodoge</label>
<input type="radio" name="mokepon" id="capipego" value="capipego">
<label for="capipego">Capipego</label>
<input type="radio" name="mokepon" id="ratigueya" value="ratigueya">
<label for="ratigueya">Ratigueya</label>
<button type="submit">Seleccionar</button>
</form>

Link Radiobox button to Input

I have 2 radio button, each valued Yes and No respectively and 1 textbox.. If I checked on No button, the input textbox will open. If checked on Yes, textbox will disabled.
This code is working fine but I want to delete content that input to the textbox if the user checked Yes
function ismcstopu() {
var chkNo = document.getElementById("radio2_ismcstop");
var mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = chkNo.checked ? false : true;
if (!mcnostopreason.disabled) {
mcnostopreason.focus();
} else {
mcnostopreason.val('');
}
}
<input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" onclick="ismcstopu()" value="Yes">Yes
<input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" onclick="ismcstopu()" value="No">No
<label for="mcnostopreason">If No, Reason:</label>
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
.val is a jQuery construct but you are using DOM
Here is a better version using eventListener
Change the document.getElementById("container") to whatever container you have (your form for example)
Note: It is often better to test true than to test false
I also added labels to the radios so we can click the yes or no too
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.name === "ismcstop") {
const mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = tgt.value === "Yes";
if (mcnostopreason.disabled) {
mcnostopreason.value = '';
} else {
mcnostopreason.focus();
}
}
})
<div id="container">
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
</div>
jQuery version
$("[name=ismcstop]").on("click", function() {
if (this.name === "ismcstop") {
const $mcnostopreason = $("#mcnostopreason");
$mcnostopreason.prop("disabled", this.value === "Yes");
if ($mcnostopreason.is(":disabled")) {
$mcnostopreason.val("");
} else {
$mcnostopreason.focus();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
mcnostopreason is not a jQuery object. therefore you could do: var mcnostopreason = $("#mcnostopreason");
Or you could just change mcnostopreason.val('') to mcnostopreason.value = '' ( this will mean you don't need to change anything else)

How to uncheck all when the other radial is picked

I create a js for my project. It almost work except that I need to uncheck all checkbox under first radial when second radial is picked.
JS
<script>
function habilitarSecciones(selected) {
var chk = $(selected);
var checked = chk.is(":checked");
var id = chk.val();
$("[id^='Grp2']").attr("disabled", true);
if (checked) {
$(".Grp2_" + id).removeAttr("disabled", false);
}
}
</script>
HTML
<div class="form-group">
<h3>Tipo</h3>
#foreach (Dominio.Tipo tipo in Model.Secciones.Select(x => x.Tipo).Distinct())
{
<label>
<input type="radio" value="#tipo.Id" name="Grp_Tipo" id='Grp_#tipo.Id' onclick="habilitarSecciones(this);" /> #tipo.Descrip
</label>
<hr />
foreach (var seccion in Model.Secciones.Where(x => x.Tipo == tipo))
{
<label>
<input type="checkbox" class="Grp2_#tipo.Id" value="#seccion.Id" name="SeccionesElegidas" id="Grp2_#seccion.Id" disabled /> #seccion.Descrip
</label>
}
<hr />
}
</div>
Please to try with $('element').prop('checked', false);

How Do I count the selected checkbox in AngularJS?

/**
* #Summary: checkAllConnectedUser function, to create album
* #param: index, productObj
* #return: callback(response)
* #Description:
*/
$scope.shardBuyerKeyIdArray = [];
$scope.countBuyer = 0;
$scope.checkAllSharedBuyer = function(isChecked) {
if (isChecked) {
if ($scope.selectAll) {
$scope.selectAll = false;
} else {
$scope.selectAll = true;
}
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
//IF ID WILL BE EXIST IN THE ARRAY NOT PSUH THE KEYID
if ($scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId) == -1) {
$scope.shardBuyerKeyIdArray.push(selectedBuyer.userTypeDto.keyId);
$scope.countBuyer++;
}
});
} else {
$scope.selectAll = false;
//USED FOR UNCHECK ALL THE DATA ONE- BY-ONE
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
var index = $scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId);
$scope.shardBuyerKeyIdArray.splice(index, 1);
$scope.countBuyer--;
});
}
}
<div class="checkbox w3-margin" ng-if="selectedSharedBuyerObjectList.length > 0">
<span class="w3-right" ng-if="countBuyer">
<h5>You are selecting {{countBuyer}} buyers!</h5>
</span>
<label>
<input type="checkbox" ng-model="selectAll" ng-click="checkAllSharedBuyer(selectAll)"/>Check All
</label>
</div>
<div id="sharedRow" class="checkbox" ng-repeat="selectedBuyer in cmnBuyer = (selectedSharedBuyerObjectList | filter : userSearchInProduct
| filter : filterUser)">
<label>
<input type="checkbox" ng-model="selectedBuyer.select"
ng-change="selectedSharedBuyer($index, selectedBuyer.select, selectedBuyer.userTypeDto.keyId)"/>
{{selectedBuyer.personName}}
</label>
</div>
I have two list in which i have to count the select all checkbox length as well as single checkbox count my problem if the user un-check the ALL checkbox Checkbox count will be return -- what's the problem in my code?
$(function(){
var count = 0;
$('#sharedRow ').find('input[type=checkbox]').on('change',function(){
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
})
$('#chkAll').on('change', function () {
if ($(this).is(':checked')) {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', true);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
else {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', false);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox w3-margin">
<span class="w3-right">
<h5 id="msg" >You are selecting 0 buyers!</h5>
</span>
<label>
<input id="chkAll" type="checkbox" />Check All
</label>
</div>
<div id="sharedRow" class="checkbox">
<label>
<input type="checkbox" value="1 Buyers" />1 Buyers
</label>
<label>
<input type="checkbox" value="2 Buyers" />2 Buyers
</label>
<label>
<input type="checkbox" value="3 Buyers" />3 Buyers
</label>
<label>
<input type="checkbox" value="4 Buyers" />4 Buyers
</label>
<label>
<input type="checkbox" value="5 Buyers" />5 Buyers
</label>
<label>
<input type="checkbox" value="6 Buyers" />6 Buyers
</label>
<label>
<input type="checkbox" value="7 Buyers" />7 Buyers
</label>
<label>
<input type="checkbox" value="8 Buyers" />8 Buyers
</label>
</div>
try this one. is it ok? if not then tell me what's wrong.
if you have a group of checkbox then you can find all selected checkbox.
$('div').find('input[type=checkbox]:checked').length;
If you only need the number
var count = $scope.selectedSharedBuyerObjectList.reduce(function(sum, item) {
return (item.select) ? sum + 1 : sum;
}, 0);
If you need the filtered array
var selected = $scope.selectedSharedBuyerObjectList.filter(function(item) {
return item.select;
});
var count = selected.length;
Or do it using plain old loop
var count = 0;
for (i = 0; i < $scope.selectedSharedBuyerObjectList.length; i++) {
if ($scope.selectedSharedBuyerObjectList.select) count++;
}

Show/Hide Combobox Dropdown with pure Javascript

I have a user control in asp.net that outputs markup similar to the following:
<div id="combobox1">
<div id="combobox1_text"><span>combobox 1</span></div>
<div id="combobox1_ddl">
<input type="checkbox" id="combobox1_$1" />
<label for="combobox1_$1">Item 1</label>
<br />
<input type="checkbox" id="combobox1_$2" />
<label for="combobox1_$2">Item 2</label>
<br />
<input type="checkbox" id="combobox1_$3" />
<label for="combobox1_$3">Item 3</label>
<br />
<input type="checkbox" id="combobox1_$4" />
<label for="combobox1_$4">Item 4</label>
<br />
<input type="checkbox" id="combobox1_$5" />
<label for="combobox1_$5">Item 5</label>
<br />
</div>
</div>
A javascript file accompanying this control has the following class (minimal code to reproduce the problem only):
ComboBox = function(cb) {
var pnlContainer = document.getElementById(cb);
var pnlComboBox = document.getElementById(cb + '_text');
var pnlDropdownList = document.getElementById(cb + '_ddl');
var isCollapsed = true;
var collapseDropdown = function() {
if (!isCollapsed) {
isCollapsed = true;
pnlDropdownList.style.display = 'none';
//-- some more custom handling code follows here --
}
};
pnlComboBox.onclick = function() {
isCollapsed = !isCollapsed;
pnlDropdownList.style.display = (isCollapsed) ? 'none' : 'block';
};
pnlContainer.onclick = function(event) {
event.stopPropagation();
};
document.addEventListener('click', function() {
collapseDropdown();
}, false);
}
And finally, on my page I create an instance of the class like this:
cb1 = new ComboBox('combobox1');
All this works fine until there is only one instance of this control. It collapses correctly whenever anything or anywhere outside the control is clicked, just as expected.
The Problem:
The problem happens when there are more than one instances of this control on the page. If one of the comboboxes is open, and user clicks on another instance of my combobox, the previous one doesn't collapse.
JsFiddle for minimal code to reproduce the problem can be found here:
https://jsfiddle.net/x8qjo79f/
I know it is happening because of event.stopPropagation() call, but don't know what to do for this.
Edit the document onclick event listener to capture the event (so it is executed before the bubbling phase) and collapse when its target is outside your combobox.
ComboBox = function(cb) {
var pnlContainer = document.getElementById(cb);
var pnlComboBox = document.getElementById(cb + '_text');
var pnlDropdownList = document.getElementById(cb + '_ddl');
var isCollapsed = true;
var collapseDropdown = function() {
if (!isCollapsed) {
isCollapsed = true;
pnlDropdownList.style.display = 'none';
//-- some more custom handling code follows here --
}
};
pnlComboBox.onclick = function() {
isCollapsed = !isCollapsed;
pnlDropdownList.style.display = (isCollapsed) ? 'none' : 'block';
};
pnlContainer.onclick = function(event) {
event.stopPropagation();
};
// Edit: Capture click event
document.addEventListener('click', function(event) {
if (!pnlContainer.contains(event.target)) collapseDropdown();
}, true);
}
cb1 = new ComboBox('combobox1');
cb2 = new ComboBox('combobox2');
#combobox1,
#combobox2 {
border: 1px solid black;
cursor: default;
width: 200px;
font-family: verdana;
font-size: 10pt;
}
#combobox1_text,
#combobox2_text {
padding: 2px;
}
#combobox1_ddl,
#combobox2_ddl {
border-top: 1px solid black;
display: none;
}
<div id="combobox1">
<div id="combobox1_text"><span>combobox 1</span></div>
<div id="combobox1_ddl">
<input type="checkbox" id="combobox1_$1" />
<label for="combobox1_$1">Item 1</label>
<br />
<input type="checkbox" id="combobox1_$2" />
<label for="combobox1_$2">Item 2</label>
<br />
<input type="checkbox" id="combobox1_$3" />
<label for="combobox1_$3">Item 3</label>
<br />
<input type="checkbox" id="combobox1_$4" />
<label for="combobox1_$4">Item 4</label>
<br />
<input type="checkbox" id="combobox1_$5" />
<label for="combobox1_$5">Item 5</label>
<br />
</div>
</div>
<br />
<input type="text" />
<br />
<input type="button" />
<br />
<input type="checkbox" />
<br />
<span>some random text in the document.. <br />blah. blah.. blah..</span>
<br />
<br />
<br />
<div id="combobox2">
<div id="combobox2_text"><span>combobox 2</span></div>
<div id="combobox2_ddl">
<input type="checkbox" id="combobox2_$1" />
<label for="combobox2_$1">Item 1</label>
<br />
<input type="checkbox" id="combobox2_$2" />
<label for="combobox2_$2">Item 2</label>
<br />
<input type="checkbox" id="combobox2_$3" />
<label for="combobox2_$3">Item 3</label>
<br />
<input type="checkbox" id="combobox2_$4" />
<label for="combobox2_$4">Item 4</label>
<br />
<input type="checkbox" id="combobox2_$5" />
<label for="combobox2_$5">Item 5</label>
<br />
</div>
</div>
You could allow the event propagation in pnlContainer.onclick but remember that the ComboBox was clicked. Inside the document click event handler, you would test if the ComboBox is the clicked one, and allow to collapse only if it is not.
The changes to the Javascript code could look like this:
ComboBox = function(cb) {
var isClicked = false;
...
pnlContainer.onclick = function(event) {
isClicked = true;
};
document.addEventListener('click', function() {
if (isClicked) {
isClicked = false;
}
else {
collapseDropdown();
}
}, false);
}

Categories

Resources