I have created a multi-select ui component where i have to push selected values to an array and show the same in a button value. I am getting the selected values in alert box but not able to get it in button.
Please help me to show the selected items values as button value as soon as the checkbox clicked.
Snippet:
function getCheckedCheckboxesFor(checkboxName) {
var checkboxes = document.querySelectorAll('input[name="' + checkboxName + '"]:checked'),
values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
return values;
}
.check-multiple {
display: inline-block;
height: 60px;
overflow-y: scroll;
border: 1px solid gray;
}
.check-multiple input {
float: left;
}
.check-multiple label {
display: inline-block;
}
.check-multiple span {
display: inline-block;
width: 100%;
}
.check-multiple input:checked~span {
background: #03f;
color: white;
}
<div class="check-multiple">
<label for="veh"><input value="car" type="checkbox" name="veh"><span>car</span></label>
<label for="veh"><input value="scooter" type="checkbox" name="veh"><span>scooter</span></label>
<label for="veh"><input value="bus" type="checkbox" name="veh"><span>bus</span></label>
</div>
<input type="button" onclick="alert(getCheckedCheckboxesFor('veh'));" value="Get Values" />
After reading your comments,
here is probably what you want to achieve:
// Added this:
var checkboxes = document.querySelectorAll('input[type=checkbox]');
checkboxes.forEach(function(chkbx) {
chkbx.onchange = function() {
document.getElementById("button").value = getCheckedCheckboxesFor(chkbx.name);
}
})
// Simplified a little this:
function getCheckedCheckboxesFor(name) {
var checkeds = document.querySelectorAll('input[name="' + name + '"]:checked'),
values = [];
checkeds.forEach(function(chkd) {
values.push(chkd.value);
});
return values;
}
.check-multiple {
display: inline-block;
height: 60px;
overflow-y: scroll;
border: 1px solid gray;
}
.check-multiple input {
float: left;
}
.check-multiple label {
display: inline-block;
}
.check-multiple span {
display: inline-block;
width: 100%;
}
.check-multiple input:checked~span {
background: #03f;
color: white;
}
<div class="check-multiple">
<label for="veh"><input value="car" type="checkbox" name="veh"><span>car</span></label>
<label for="veh"><input value="scooter" type="checkbox" name="veh"><span>scooter</span></label>
<label for="veh"><input value="bus" type="checkbox" name="veh"><span>bus</span></label>
</div>
<input id="button" type="button" onclick="alert(getCheckedCheckboxesFor('veh'));" value="Get Values" />
⋅
⋅
⋅
Then, as you MUST want to use this code on multiple elements, I did the following:
As you should avoid inline JavaScript, I removed the function call from the HTML,
I added a data attribute on the buttons, and some other forEach() to work with multiple elements,
I added a 'None selected' when you tick and then untick something. (I didn't like having an empty button),
I've also added the disabled property when 'None selected', just because we can.
Here is a working snippet with all of it:
// Added this
// Made it for multiples, too!
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var buttons = document.querySelectorAll('input[type=button]');
checkboxes.forEach(function(chkbx, index) {
chkbx.onchange = function() {
var name = chkbx.name;
var button = document.querySelector('input[type=button][data=' + name + ']')
button.value = getCheckedCheckboxesFor(name);
// Added some code to modify button if no checkbox is selected
button.removeAttribute("disabled");
if (button.value == '') {
button.value = 'None selected';
button.setAttribute("disabled", true);
}
}
})
// As you should avoid inline JS, added this too:
buttons.forEach(function(button, index) {
button.onclick = function() {
var name = this.getAttribute('data'); // Get data attribute
alert(getCheckedCheckboxesFor(name));
}
})
// Simplified a little this one:
function getCheckedCheckboxesFor(name) {
var checkeds = document.querySelectorAll('input[name="' + name + '"]:checked'),
values = [];
checkeds.forEach(function(chkd) {
values.push(chkd.value);
});
return values;
}
.check-multiple {
display: inline-block;
height: 60px;
overflow-y: scroll;
border: 1px solid gray;
}
.check-multiple input {
float: left;
}
.check-multiple label {
display: inline-block;
}
.check-multiple span {
display: inline-block;
width: 100%;
}
.check-multiple input:checked~span {
background: #03f;
color: white;
}
<div class="check-multiple">
<label for="veh"><input value="car" type="checkbox" name="veh"><span>car</span></label>
<label for="veh"><input value="scooter" type="checkbox" name="veh"><span>scooter</span></label>
<label for="veh"><input value="bus" type="checkbox" name="veh"><span>bus</span></label>
</div>
<br>
<input data="veh" type="button" value="Select to get values" disabled/>
<br>
<br>
<div class="check-multiple">
<label for="veh"><input value="car" type="checkbox" name="veh2"><span>car</span></label>
<label for="veh"><input value="scooter" type="checkbox" name="veh2"><span>scooter</span></label>
<label for="veh"><input value="bus" type="checkbox" name="veh2"><span>bus</span></label>
</div>
<br>
<input data="veh2" type="button" value="Select to get values" disabled/>
Hope it helps!
Your question is a bit weird formulated, is this what you are trying to accomplish?
EDIT: used onchange event to trigger the changing value of the button text on the checkboxes
function getCheckedCheckboxesFor(checkboxName) {
}
function myFunction(val) {
var checkboxes = document.querySelectorAll('input[name="' + val + '"]:checked'),
values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
document.getElementById("demo").value = values;
}
.check-multiple {
display: inline-block;
height: 60px;
overflow-y: scroll;
border: 1px solid gray;
}
.check-multiple input {
float: left;
}
.check-multiple label {
display: inline-block;
}
.check-multiple span {
display: inline-block;
width: 100%;
}
.check-multiple input:checked~span {
background: #03f;
color: white;
}
<div class="check-multiple">
<label for="veh"><input value="car" type="checkbox" name="veh" onchange="myFunction('veh')"><span>car</span></label>
<label for="veh"><input value="scooter" type="checkbox" name="veh" onchange="myFunction('veh')"><span>scooter</span></label>
<label for="veh"><input value="bus" type="checkbox" name="veh" onchange="myFunction('veh')"><span>bus</span></label>
</div>
<input type="button" onclick="alert(getCheckedCheckboxesFor('veh'));" value="Get Values" id="demo" />
Related
Evening all, I've spent the last few days trying to figure out how to validate multiple radio groups in javascript. I aim to determine if the user has made a selection; if not, prompt them via an error message.
I've dug around Stack and Google etc. But no matter what I try/find, I just can't seem to get the behaviour I'm looking for. The questions/resources I've found so far have guided me to my current example (Shown Below), but I'm hoping one of you lovely people could guide me across the finish line.
Specifically, I'm looking for an example of how to validate all radio groups, making sure that the user has made a selection within each. (I would appreciate good commenting and explaining each step, as the loops are pretty challenging for me to understand.)
Thanks in advance. 😅👌
I've attached below a complete snippet with my workings inside; I've tweaked the snippet to cut out all of the non-essential stuff in the hopes it makes it easier to understand.
EDIT:
Forgot to mention the problems with the below code. The below code seems to validate on certain selection combinations but fails on others, I suspect it might be a loop error, but I'll admit when I don't think I understand them well enough.
EDIT:
For those yet to come, I've accepted #KooiInc's answer because it answers the question. Though Mister Jojo is correct, I should be using forms and HTML5 for validation. Stupid oversight that ended up in me wasting a tonne of time. 😅 Ah, well, it's all a learning experience. 👍👌
Example Snippet
class radioChecks {
// Constructor.
constructor() {
this.inputs = document.querySelectorAll("input");
this.radioGroups = document.querySelectorAll(".radioGroup");
this.errors = document.getElementById("errors");
this.bindEvents();
}
// Bind Events.
bindEvents() {
for (let i = 0; i < this.inputs.length; i++) {
this.inputs[i].addEventListener("click", function(e) {
if (e.target.dataset.direction) {
e.target.dataset.direction === "next"
this.validate();
}
}.bind(this));
}
}
validate() {
const _this = this;
function isRadioGroupValid() {
let checked = false;
let inputName = "";
for (let i = 0; i < _this.radioGroups.length; i++) {
const radios = _this.radioGroups[i].querySelectorAll('[type="radio"]');
for (let j = 0; j < radios.length; j++) {
radios[i].checked ? checked = true : checked = false;
inputName = radios[i].name;
}
}
!checked
?
_this.errorHandler(_this, `Please select an option for ${inputName}.`, true) :
_this.errorHandler(_this, "", false);
}
isRadioGroupValid();
console.log("All radio groups have selection.");
return true;
}
errorHandler(_this, message, error) {
// Show any errors.
function showErrors(message) {
_this.errors.innerHTML = message;
_this.errors.classList.add("invalid");
throw new Error(message);
}
// Clear any existing errors.
function clearErrors() {
_this.errors.innerHTML = "";
_this.errors.classList.remove("invalid");
}
// if error true. Show error.
error ? showErrors(message) : clearErrors();
}
}
new radioChecks();
* {
text-align: center;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, Arial, sans-serif;
}
.radioGroup {
display: flex;
justify-content: center;
align-items: center;
/* flex-flow: row nowrap; */
flex-direction: row;
flex-wrap: nowrap;
align-content: space-between;
gap: 1em;
max-width: 640px;
margin: 0 auto;
}
.radioGroup:first-of-type {
margin-top: 3em;
}
#media screen and (max-width: 768px) {
flex-direction: column;
}
.radioOption {
flex-grow: 1;
width: 100%;
margin-bottom: 1em;
}
input[type="radio"] {
position: absolute;
left: -9999px;
opacity: 0;
z-index: 100;
}
label {
display: block;
padding: 0.5em 1em;
border: 1px solid #999;
color: #999;
width: 100%;
cursor: pointer;
transition: all 0.2s ease;
}
input[type="radio"]:checked+label {
border: 1px solid #000;
color: #000;
transition: all 0.2s ease;
}
input[type="button"] {
margin-top: 3em;
background-color: #ddd;
border: none;
color: #000;
padding: 0.5em 2em;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
input[type="button"]:hover {
background-color: #ccc;
}
#errors.invalid {
display: block;
}
#errors {
display: none;
color: #842029;
background-color: #f8d7da;
border: 1px solid #f5c2c7;
font-weight: bold;
padding: 0.5em 2em;
width: 300px;
margin: 2em auto;
}
<div class="radioGroup">
<div class="radioOption">
<input type="radio" id="radioOne" name="group_one" value="Foo">
<label for="radioOne">My Foo Radio</label>
</div>
<div class="radioOption">
<input type="radio" id="radioTwo" name="group_one" value="Bar">
<label for="radioTwo">My Bar Radio</label>
</div>
</div>
<div class="radioGroup">
<div class="radioOption">
<input type="radio" id="radioThree" name="group_two" value="Baz">
<label for="radioThree">My Baz Radio</label>
</div>
<div class="radioOption">
<input type="radio" id="radioFour" name="group_two" value="Qux">
<label for="radioFour">My Qux Radio</label>
</div>
</div>
<div class="btn">
<input type="button" data-direction="next" value="Next" />
</div>
<div id="errors"> Testing! </div>
You can use a css-selector to determine the radio check states. Here a minimal example for that:
document.addEventListener(`click`, evt => {
if (evt.target.id === `allchecked`) {
console.clear();
const bothChecked = document
.querySelectorAll(`.rGroup input[type='radio']:checked`)
.length === 2;
console.log(`both groups checked? ${
bothChecked ? `Yep`: `Nope`}`);
}
})
<div class="rGroup" id="group1">
<input type="radio" name="rg1"> one
<input type="radio" name="rg1"> two
<input type="radio" name="rg1"> three
</div>
<div class="rGroup" id="group2">
<input type="radio" name="rg2"> one
<input type="radio" name="rg2"> two
<input type="radio" name="rg2"> three
</div>
<button id="allchecked">both checked?</button>
Sample code using HTML5 form validation:
const myForm = document.forms['my-form']
myForm.onsubmit = e =>
{
e.preventDefault() // disable form submitting
console.clear()
console.log(Object.fromEntries(new FormData(myForm).entries()))
}
myForm.reset =_=>
{
console.clear()
}
<form name="my-form">
<fieldset>
<legend> group A </legend>
<label><input type="radio" name="rg1" value="A_1" required> one </label>
<label><input type="radio" name="rg1" value="A_2"> two </label>
<label><input type="radio" name="rg1" value="A_3"> tree </label>
</fieldset>
<fieldset>
<legend> group B </legend>
<label><input type="radio" name="rg2" value="B_1" required> one </label>
<label><input type="radio" name="rg2" value="B_2"> two </label>
<label><input type="radio" name="rg2" value="B_3"> tree </label>
</fieldset>
<button> validation </button>
<button type="reset"> reset </button>
</form>
I have already created a form in html and linked it with my style sheet and also JavaScript page.
My problem is displaying the result on the form.
Can someone please take a look at the JavaScript code and tell me what I am doing wrong?
See the snippet for more details
// Percentage Calculator
const myForm = document.getElementById('my-form');
myForm.onsubmit = e=>e.preventDefault() // disable form submit
;
myForm.oninput = percentageCalculator;
function percentageCalculator(amount, percent) {
return ((percent *amount) / 100).toFixed(2)
}
myForm.result.value = percentageCalculator()
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br><br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
If you want to make result instantly on click of the input boxes then, make addEventListerner to input elements then get the value inside percentageCalculator and make calculation accordingly..
I have not modified anything from your HTML and only modified the JS part..
const myForm = document.getElementById('my-form');
const percent = document.querySelector('[name="percent"]');
const amount = document.querySelector('.amount');
const result = document.querySelector('[name="result"]');
function percentageCalculator() {
result.value = ((percent.value * amount.value) / 100).toFixed(2)
}
myForm.addEventListener('submit', e=>e.preventDefault())
myForm.addEventListener('input', percentageCalculator)
// myForm.result.value = percentageCalculator()
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br><br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
If it is possible for you to modify HTML template then you can add name attribute to the amount input as well then you can get the element with myForm.inputName..
Alternative solution: https://codepen.io/Maniraj_Murugan/pen/KKpdgXo
Use oninput as I did below. Also give the amount input field a name. it's missing in the OP.
// Percentage Calculator
const myForm = document.getElementById('my-form');
myForm.oninput = () => {
myForm.result.value = percentageCalculator(myForm.amount.value, myForm.percent.value);
}
function percentageCalculator(amount, percent) {
return ((percent * amount) / 100).toFixed(2)
}
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" name="amount" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
Pass the parameters into the function as a local scope and return the result back.
function percentageCalculator(amount,percent) {
return ((percent *amount) / 100).toFixed(2)
}
myForm.result.value = percentageCalculator()
// Percentage Calculator
const calculatedResult = document.getElementById('result');
function mySubmitFunction(e) {
e.preventDefault();
const percent = document.getElementById('percent').value;
const amount = document.getElementById('amount').value;
calculatedResult.value = percentageCalculator(amount,percent);
return false;
}
function percentageCalculator(amount,percent) {
return ((percent *amount) / 100).toFixed(2)
}
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" onsubmit="return mySubmitFunction(event)" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" id="percent" name="percent" step=any min=0> % of </append>
<label><input type="number" id="amount" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output id="result" name="result" value='0'></output>
<br><br>
<button type="submit">Calculate!</button>
</fieldset>
</form>
Your mistake:
Submit button instead of reset
Prevent default once it's submitted
reference element using ID
I'm trying to create a change function that creates a div for each checked checkbox selection and also removes the div when it's unchecked.
Inside these new divs I want to send the checkbox's img src as well.
*NOTE** My current JS is as far as I got and the second function only takes the img src from the selected checkbox and sends it to the image with id="loc-selected".
$(".loc-check").change(function(event) {
var x = $(this).val();
if ($(this).prop("checked") == true) {} else {}
});
function changeImg(elm) {
var val = elm.value;
var img = document.getElementById("img-" + val);
var src = img.src;
var imgSelectedRadio = document.getElementById("loc-selected");
imgSelectedRadio.src = src;
}
#loc-selected {
height: 50px;
width: 50px;
}
#loc-checkboxs {
display: flex;
padding: 20px;
}
#loc-checkboxs label {
display: block;
height: 38px;
width: 38px;
cursor: pointer;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loc-checkboxs">
<label for="usa">
<input class="loc-check" type="checkbox" id="usa" value="usa" onchange="changeImg(this)"/>
<span><img id="img-usa" src="https://uploads-ssl.webflow.com/57e5747bd0ac813956df4e96/5a2f052996bde90001f96632_united-states-of-america.svg"><span>
</label>
<label for="canada">
<input class="loc-check" type="checkbox" id="canada" value="canada" onchange="changeImg(this)"/>
<span><img id="img-canada" src="https://uploads-ssl.webflow.com/57e5747bd0ac813956df4e96/5a2cd7b0937442000184b147_canada.svg"><span>
</label>
<label for="uk">
<input class="loc-check" type="checkbox" id="uk" value="uk" onchange="changeImg(this)"/>
<span><img id="img-uk" src="https://uploads-ssl.webflow.com/57e5747bd0ac813956df4e96/5a985a90ec8f79000104514a_united-kingdom.svg"><span>
</label>
</div>
<div class="new-div-wrapper">
<div class="new-div">
<img id="loc-selected"></img>
</div>
</div>
I modified your code to dynamically add items with the same class as the values of the the checkboxes. It then automatically removes it if you uncheck.
$("input.loc-check").change(function(event) {
var value = $(this).val();
if ($(this).is(":checked")) {
$(".new-div-wrapper").append($(this).next().clone().wrapAll("<div class='new-div'></div>").parent().addClass(value));
} else {
$(".new-div-wrapper ." + value).remove();
}
});
#loc-selected {
height: 50px;
width: 50px;
}
#loc-checkboxs {
display: flex;
padding: 20px;
}
#loc-checkboxs label {
display: block;
height: 38px;
width: 38px;
cursor: pointer;
position: relative;
}
.new-div {
width:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loc-checkboxs">
<label for="usa">
<input class="loc-check" type="checkbox" id="usa" value="usa"/>
<span><img id="img-usa" src="https://uploads-ssl.webflow.com/57e5747bd0ac813956df4e96/5a2f052996bde90001f96632_united-states-of-america.svg" \></span>
</label>
<label for="canada">
<input class="loc-check" type="checkbox" id="canada" value="canada"/>
<span><img id="img-canada" src="https://uploads-ssl.webflow.com/57e5747bd0ac813956df4e96/5a2cd7b0937442000184b147_canada.svg" \></span>
</label>
<label for="uk">
<input class="loc-check" type="checkbox" id="uk" value="uk"/>
<span><img id="img-uk" src="https://uploads-ssl.webflow.com/57e5747bd0ac813956df4e96/5a985a90ec8f79000104514a_united-kingdom.svg" \></span>
</label>
</div>
<div class="new-div-wrapper">
</div>
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
<form>
<label>Department</label>
<div>
<div class="selectBox" onclick="showCheckboxes()">
<select class="form-control">
<option>-Select a Department-</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label>
<input type="checkbox" id="1" />bscs<br>
<input type="checkbox" id="1" />bsit<br>
<input type="checkbox" id="1" />mscs<br>
<input type="checkbox" id="1" />msit<br>
<input type="checkbox" id="1" />bba<br>
<input type="checkbox" id="1" />Dpt<br>
</label>
</div>
</div>
</form>
I am using checkbox in drop down list and is filled by dynamic values and i want to get checked values from the list and submit these values in the form.
Controller's Action method code
FYP_DB_Entities obj = new FYP_DB_Entities();
public ActionResult Index()
{
ViewBag.dept = obj.Departments.ToList();
return View();
}
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
<div>
<div class="selectBox" onclick="showCheckboxes()">
<select class="form-control">
<option>-Select a Department-</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
#foreach (var s in ViewBag.dept) {
<label for="#s.Department_Id"><input type="checkbox" id="#s.Department_Id" />#s.Department_Id</label>
}
</div>
</div>
Here is the screenshot of the dropdownlist before Clicking on it
After Clicking on it
The easiest and tricky way to do this is to keep checkboxes code inside the Form tag and use the same name for all the checkboxes with different ids (to make them work for "for" attribute of label tag). Also, set the value of checkbox to departmentId. Your code will look like this:
<div id="checkboxes">
#foreach (var s in ViewBag.dept) {
<label for="#s.Department_Id"><input type="checkbox" id="#s.Department_Id" name="selectedDepartmentIds" value="#s.Department_Id" />#s.Department_Id</label>
}
</div>
add a new parameter at controller's action with name selectedDepartmentIds of type array. When you submit the form you will get selected department ids.
I have a group of radio buttons, and a submit button. When I click on the submit button a message is shown telling me which radio button I clicked on. What I want to do now is change the color of the selected radio button, how can I do it? I have tried many things without success. Here is the code
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
}
}
}
<input type="radio" name="gender" class="one" value="Male" />Male <br>
<input type="radio" name="gender" class="one" value="Female" />Female<br>
<input type="radio" name="gender" class="one" value="Other" />Other<br>
<div id="display"> </div>
<button onclick="selectedButton()">Submit</button>
You can wrap the radio buttons to a div and then apply a CSS class when selected. Then, in your CSS, you can define the necessary styles.
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
optionContainer[i].parentElement.classList.add('selected');
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
} else {
optionContainer[i].parentElement.classList.remove('selected');
}
}
}
.selected {
color: Red;
}
<div>
<input type="radio" name="gender" class="one" value="Male" />Male
</div>
<div>
<input type="radio" name="gender" class="one" value="Female" />Female
</div>
<div>
<input type="radio" name="gender" class="one" value="Other" />Other
</div>
<div id="display"> </div>
<button onclick="selectedButton()">Submit</button>
You can enclose the whole input element in a span and using parentNode change the color of the full radio button
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
optionContainer[i].style.backgroundColor = "blue";
optionContainer[i].parentNode.style.backgroundColor = "blue";
optionContainer[i].parentNode.style.color = "yellow"
} else {
optionContainer[i].style.backgroundColor = "";
optionContainer[i].parentNode.style.backgroundColor = "";
optionContainer[i].parentNode.style.color = ""
}
}
}
<span><input type="radio" name="gender" class="one" value="Male" />Male</span> <br>
<span><input type="radio" name="gender" class="one" value="Female" />Female</span><br>
<span><input type="radio" name="gender" class="one" value="Other" />Other</span><br>
<div id="display"> </div>
<button onclick="selectedButton()">Submit</button>
You can enclose the labels in span and using nextSibling color them with the radio button
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
optionContainer[i].style.backgroundColor = "blue";
optionContainer[i].nextSibling.style.backgroundColor = "blue";
optionContainer[i].nextSibling.style.color = "yellow"
} else {
optionContainer[i].style.backgroundColor = "";
optionContainer[i].nextSibling.style.backgroundColor = "";
optionContainer[i].nextSibling.style.color = ""
}
}
}
<input type="radio" name="gender" class="one" value="Male" /><span>Male</span> <br>
<input type="radio" name="gender" class="one" value="Female" /><span>Female</span><br>
<input type="radio" name="gender" class="one" value="Other" /><span>Other</span><br>
<div id="display"> </div>
<button onclick="selectedButton()">Submit</button>
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
optionContainer[i].style.backgroundColor = "red";
}
else {
optionContainer[i].style.backgroundColor = "";
}
}
}
You can customize the style of radio button as your wish. Direct styling on radio will not work.
Below is an example.
You have not provided the style for selected class as well. Please add that to see the style change.
This is the style you needed.
.container.selected input:checked ~ .checkmark {
background-color: red;
}
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
optionContainer[i].parentElement.classList.add("selected");
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
} else {
optionContainer[i].parentElement.classList.remove("selected");
}
}
}
/* The container */
.container {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default radio button */
.container input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/* Create a custom radio button */
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
border-radius: 50%;
}
/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
background-color: #ccc;
}
/* When the radio button is checked, add a blue background */
.container input:checked ~ .checkmark {
background-color: #2196f3;
}
/* Create the indicator (the dot/circle - hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the indicator (dot/circle) when checked */
.container input:checked ~ .checkmark:after {
display: block;
}
/* Style the indicator (dot/circle) */
.container .checkmark:after {
top: 9px;
left: 9px;
width: 8px;
height: 8px;
border-radius: 50%;
background: white;
}
.container.selected input:checked ~ .checkmark {
background-color: red;
}
<h1>Custom Radio Buttons</h1>
<label class="container"
>One
<input type="radio" class="one" checked="checked" name="radio" value="One" />
<span class="checkmark"></span>
</label>
<label class="container"
>Two
<input type="radio" class="one" name="radio" value="Two" />
<span class="checkmark"></span>
</label>
<label class="container"
>Three
<input type="radio" name="radio" class="one" value="Three" />
<span class="checkmark"></span>
</label>
<label class="container"
>Four
<input type="radio" class="one" name="radio" value="Four" />
<span class="checkmark"></span>
</label>
<div id="display"></div>
<button onclick="selectedButton()">Submit</button>