Show Label of multiple checked checkbox with javascript - javascript

I have a list of a few dozen checkboxes as shown in example below. If a user checks several of them I need to show at the bottom of the page which ones was checked, such as:
Option One
Option three
Was trying to do this with onClick so it will add or remove to the list at the bottom of the page when a checkbox is clicked or un-clicked but not able to get it to work.
Example of my checkboxes
HTML
.checkboxes label {
font-family: Open Sans Italic;
font-size: 12px;
color: white;
font-weight: bold;
border-radius: 20px 20px 20px 20px;
background: blue;
padding: 1px 6px;
text-align: left;
}
input[type=checkbox]:checked+label {
color: white;
background: green;
}
<div class="checkboxes">
<input type="checkbox" name="lra" id="1adm" value="selected">
<label for="1adm" class="highlight">Option one</label>
<br>
<input type="checkbox" name="lra" id="2adm" value="selected">
<label for="2adm" class="highlight">Option two</label>
<br>
<input type="checkbox" name="lra" id="3adm" value="selected">
<label for="3adm" class="highlight">Option three</label>
<br>
<input type="checkbox" name="lra" id="4adm" value="selected">
<label for="4adm" class="highlight">Option four</label>
<br>
</div>
Any suggestion on how I can do this with javascript with multiple boxes checked to show at the bottom of the page using onClick of which ones is clicked or not, showing the label such as:
Option one
Option four
if One and four is checked.

You can achieve it with many approaches. In my implementation, I assign to each checkbox an onClick event handler that adds or removes from a Set , its value, and after iterates the Set, dumping inside a container a string with all the selected checkboxes:
// set to store the selected checkboxes values
let items = new Set();
// reference to the dumping container
let resultContainer= document.getElementById('result')
// onclick event handler
function updateItems(e){
// value of the clicked checkbox
let value = e.target.value;
// if value is already in the Set, remove it (input unchecked)
if(items.has(value)) items.delete(value)
// if value is not in in the set, insert it (input checked)
else items.add(value)
//
// set updated ! now dump its contents...
//
// empty string
let result = '';
// iterate Set, and generate string with selected values
items.forEach(i=> result += i +'<br>')
// dump string
resultContainer.innerHTML=result;
}
// select all checkboxes and assign the onclick event handler
let inputs = Array.from (document.querySelectorAll('input') )
inputs.forEach(i => i.onclick=updateItems )
<div class="checkboxes">
<input type="checkbox" name="lra" id="1adm" value="one">
<label for="1adm" class="highlight">Option one</label>
<br>
<input type="checkbox" name="lra" id="2adm" value="two">
<label for="2adm" class="highlight">Option two</label>
<br>
<input type="checkbox" name="lra" id="3adm" value="three">
<label for="3adm" class="highlight">Option three</label>
<br>
<input type="checkbox" name="lra" id="4adm" value="four">
<label for="4adm" class="highlight">Option four</label>
<br>
</div>
<br>
<div>Selected values</div>
<div id="result"></div>
Note : This will only work, if the initial state of all checkboxes is Unchecked

This can work with onClick event on each checkbox and some Javascript.
<input type="checkbox" name="lra" id="1adm" value="selected" onclick="myFunction('1adm')">
<div id="footer" />
<script>
function myFunction(checkId) {
var checkBox = document.getElementById(checkId);
var text = document.getElementById("footer");
if (checkBox.checked == true){
//add it to footer text
} else {
//remove from footer text
}
}
</script>

Try out this example, although code could have been reasonably short :)
let selector = 'input[type="checkbox"][name="lra"]';
let updateStatus = function() {
let labels = [];
Array.prototype.slice.call(document.querySelectorAll(selector + ':checked + label')).forEach(function(l) {
labels.push(l.textContent || l.innerHTML);
});
document.querySelector('#checkStatus').innerHTML = (labels.join('<br/>') || 'Kindly choose from above options');
};
document.addEventListener('DOMContentLoaded', function() {
Array.prototype.slice.call(document.querySelectorAll(selector)).forEach(function(c) {
c.addEventListener('click', function(e) {
e.stopPropagation();
updateStatus();
});
});
updateStatus(); /* run on page load */
});
.checkboxes label {
font-family: Open Sans Italic;
font-size: 12px;
color: white;
font-weight: bold;
border-radius: 20px 20px 20px 20px;
background: blue;
padding: 1px 6px;
text-align: left;
}
input[type=checkbox]:checked+label {
color: white;
background: green;
}
#checkStatus {
border-top: 1px solid #ccc;
padding: 1rem;
margin-top: .3rem;
}
<div class="checkboxes">
<input type="checkbox" name="lra" id="1adm" value="selected">
<label for="1adm" class="highlight">Option one</label>
<br>
<input type="checkbox" name="lra" id="2adm" value="selected">
<label for="2adm" class="highlight">Option two</label>
<br>
<input type="checkbox" name="lra" id="3adm" value="selected">
<label for="3adm" class="highlight">Option three</label>
<br>
<input type="checkbox" name="lra" id="4adm" value="selected">
<label for="4adm" class="highlight">Option four</label>
<br>
</div>
<div id="checkStatus"></div>

Related

How do I listen for onclick on a set of radio buttons?

I am trying to implement a system where the user can only select one button at a time.
So there are a set of colors 'Red, Blue, Black, etc'. If the user clicks on 'Red' label it should receive the class 'check'.
If the user decides they want 'Blue' label then the 'check' should be removed from 'Red' label to be on 'Blue' label now.
I cannot simply use the document.querySelectorAll().addEventListener() since this is react.
For example in vanilla JS, I could easily do something like this:
const colorBtns = document.querySelectorAll('.color-radio-btn');
let checkedBtn = 0;
let checkedsizeBtn = 0;
let color;
colorBtns.forEach((item,i) => {
item.addEventListener('click', () => {
colorBtns[checkedBtn].classList.remove('check');
item.classList.add('check');
checkedBtn = i;
color = item.innerHTML;
})
})
And here is my react snippet:
const ShowProduct = () => {
return(
<div className='product-details'>
<input type="radio" name="color" value="Black" hidden id="black-color"/>
<label htmlFor="black-color" className="color-radio-btn">Black</label>
<input type="radio" name="color" value="Red" hidden id="red-color"/>
<label htmlFor="red-color" className="check color-radio-btn">Red</label>
<input type="radio" name="color" value="White" hidden id="white-color"/>
<label htmlFor="white-color" className="color-radio-btn">White</label>
<input type="radio" name="color" value="Yellow" hidden id="yellow-color"/>
<label htmlFor="yellow-color" className="color-radio-btn">Yellow</label>
<input type="radio" name="color" value="Green" hidden id="green-color"/>
<label htmlFor="green-color" className="color-radio-btn">Green</label>
<input type="radio" name="color" value="Purple" hidden id="purple-color"/>
<label htmlFor="purple-color" className="color-radio-btn">Purple</label>
<input type="radio" name="color" value="Purple" hidden id="blue-color"/>
<label htmlFor="blue-color" className="color-radio-btn">Blue</label>
<input type="radio" name="color" value="Purple" hidden id="orange-color"/>
<label htmlFor="orange-color" className="color-radio-btn">Orange</label>
<input type="radio" name="color" value="Custom" hidden id="custom-color"/>
<label htmlFor="custom-color" className="color-radio-btn">Custom</label>
<input type="radio" name="color" value="NotCustom" hidden id="not-custom-color"/>
<label htmlFor="not-custom-color" className="color-radio-btn">1-Color</label>
</div>
);
}
ReactDOM.render(<ShowProduct />, document.getElementById("root"));
.product-details .color-radio-btn,
.product-details .size-radio-btn{
display: inline-block;
width: 70px;
height: 70px;
text-align: center;
font-size: 14px;
border: 1px solid #383838;
border-radius: 50%;
margin: 10px;
margin-left: 0;
line-height: 60px;
text-transform: uppercase;
color: #383838;
cursor: pointer;
}
.product-details .color-radio-btn.check,
.product-details .size-radio-btn.check{
background: #383838;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
This is reactJs. So you can do this using state manipulation... You should take a event handler for onclick.. then you will update the class check using value from state.like below
state:{
selectedColor:'Red'
}
onClickHandler=(event)=>{
this.setState({selectedColor:event.target.value});
}
and html like this..
<input type="radio" checked={this.state.selectedColor==='Black'} name="color" value="Black" hidden id="black-color" onClick={this.onClickHandler}/>
<label htmlFor="black-color" className={"color-radio-btn"+(this.state.selectedColor==='Black'?' check':'')}>Black</label>
<input type="radio" checked={this.state.selectedColor==='Red'} name="color" value="Red" hidden id="red-color"/>
<label htmlFor="red-color" className={"color-radio-btn"+(this.state.selectedColor==='Red'?' check':'')} onClick={this.onClickHandler}>Red</label>
There is a strong chance you can solve this with CSS only:
.product-details input:checked + label{
background: #383838;
color: #fff;
}
This will style the label following a checked element contained in the .product-details element.

Compare the value of a checked radio button and the submit button value

I am trying to make a multiple choice quiz that uses radio buttons and a <button> inside a <fieldset>. The correct answer is stored inside the value attribute of the <button> and I want to compare the value of a checked radio button if it matches the value of the associated (in its own fieldset) <button>. However, I am not getting any result on the console on button click.
The steps I have done or am trying to do are below:
Get each fieldset
Get each fieldset's radio buttons
Get the associated fieldset button
Add a click event listener for the button to check if the value of
each fieldset radio button matches the value of its associated
button
If the button is clicked, check if the checked radio button value
matches the button value in that fieldset, console.log("CORRECT"),
else if wrong, console.log("WRONG"), else
console.log("SKIPPED").
var quizArea = document.getElementById("quiz-area");
var fieldsets = document.getElementsByTagName("fieldset"); // step 1
//console.log(fieldsets, fieldsets.length, typeof fieldsets);
for (var s = 0; s < fieldsets.length; s++) {
var fieldsetChoices = fieldsets[s].querySelectorAll("input[type=radio]"); // step 2 //console.log("fieldsetChoices[s]",fieldsetChoices[s]);
for (var i; i < fieldsetChoices.length; i++) { //console.log("fieldsetChoices[i]",fieldsetChoices[i];
var fieldsetButton = fieldsets[s].querySelector("button[type=button]"); // step 3
//console.log("fieldsetButton", fieldsetButton, fieldsetButton.value, typeof fieldsetButton);
fieldsetButton.addEventListener("click", function() { // step 4
if (fieldsetChoices[i].checked) {
if (fieldsetChoices[i].value == fieldsetButton.value) { // step 5
console.log("CORRECT", fieldsetChoices[i].value);
} else {
console.log("WRONG", fieldsetChoices[i].value);
}
} else {
console.log("SKIPPED", fieldsetChoices[i].value);
}
});
}
}
fieldset {
border: 2px solid gray;
margin: 0.5rem auto;
}
legend {
font-weight: bold;
}
label {
display: block;
margin: .5rem;
white-space: nowrap;
width: 100%;
}
/*legend>*{text-align:center;}*/
input[type=radio] {
float: left;
margin-right: .5rem;
}
.submit-button {
display: block;
margin: .5rem auto;
text-align: center;
}
<div id='quiz-area'>
<fieldset>
<legend>What is the capital of Indonesia?</legend>
<label><input type="radio" class="quiz-choices" id="indonesia-jakarta-0" name="Indonesia" value="Jakarta">Jakarta</label>
<label><input type="radio" class="quiz-choices" id="indonesia-kuala-lumpur-0" name="Indonesia" value="Kuala Lumpur">Kuala Lumpur</label>
<label><input type="radio" class="quiz-choices" id="indonesia-manila-0" name="Indonesia" value="Manila">Manila</label>
<button type="button" value="Jakarta">Submit</button>
</fieldset>
<fieldset>
<legend>What is the capital of Malaysia?</legend>
<label><input type="radio" class="quiz-choices" id="malaysia-jakarta-1" name="Malaysia" value="Jakarta">Jakarta</label>
<label><input type="radio" class="quiz-choices" id="malaysia-manila-1" name="Malaysia" value="Manila">Manila</label>
<label><input type="radio" class="quiz-choices" id="malaysia-kuala-lumpur-1" name="Malaysia" value="Kuala Lumpur">Kuala Lumpur</label>
<button type="button" value="Kuala Lumpur">Submit</button>
</fieldset>
<fieldset>
<legend>What is the capital of Philippines?</legend>
<label><input type="radio" class="quiz-choices" id="philippines-jakarta-2" name="Philippines" value="Jakarta">Jakarta</label>
<label><input type="radio" class="quiz-choices" id="philippines-kuala-lumpur-2" name="Philippines" value="Kuala Lumpur">Kuala Lumpur</label>
<label><input type="radio" class="quiz-choices" id="philippines-manila-2" name="Philippines" value="Manila">Manila</label>
<button type="button" value="Manila">Submit</button>
</fieldset>
</div>

Buttons with input radio types inserted

I would like to create html buttons with input radio type inserted into the buttons. When one clicks the buttons the input radio type is checked. I used this code but whenever I click the button the input radio button isn't checked. How do I make it work?:
<button class="button">
<input type="radio" name="input" id="choice-1" value="0">Chlorophyll
</button>
document.querySelector('.button').addEventListener('click', function(){
document.querySelector('#choice-1').checked;
});
Interactive Elements
An interactive element within an interactive element will no longer function as an interactive element.
HTML
The following demo uses a <label> as a button synced to a <input type="checkbox"> by using the for attribute and the <input> #id as it's value.
JavaScript
The details are commented in the demo below, the following list provides references concerning the JavaScript in the demo:
HTMLFormControlsCollection
Event Delegation
Event.target
Event.currentTarget
-
Demo
Details commented in demo
// Reference the <form>
var ui = document.forms['ui'];
// Register change event on <form>
ui.addEventListener('change', chx);
function chx(e) {
// Reference <output>
var out = ui.out;
// Reference clicked element
var tgt = e.target;
// if clicked element is NOT element registered to event
if (tgt !== e.currentTarget) {
// Set <output> to display the #id and value of checked
out.value = `ID: ${tgt.id} | Value: ${tgt.value}`;
}
}
html,
body {
font: 700 small-caps 16px/1.5 Consolas;
}
form * {
font: inherit
}
label {
letter-spacing: 2px;
display: inline-block;
padding: 1px 5px;
color: gold;
border: 3px ridge gold;
border-radius: 8px;
background: rgba(0, 0, 0, 0.6);
user-select: none;
cursor: pointer;
width: 110px;
}
[type=radio] {
transform: translateY(2.5px);
}
#out {
display: block;
text-align: center;
color: tomato;
}
<form id='ui'>
<label for='rad0'>Radio 1
<input id='rad0' name='rad' type='radio' value='0'>
</label>
<label for='rad1'>Radio 2
<input id='rad1' name='rad' type='radio' value='1'>
</label>
<label for='rad2'>Radio 3
<input id='rad2' name='rad' type='radio' value='2'>
</label><br><br>
<output id='out'></output>
</form>
You need to do document.querySelector('#choice-1').checked = true; as .checked needs to assign with a boolean value.
document.querySelector('.button').addEventListener('click', function() {
document.querySelector('#choice-1').checked = true;
});
<button class="button">
<input type="radio" name="input" id="choice-1" value="0">Chlorophyll
</button>

get the selected dropdown value in the inputfield instead of placeholder using javascript

I want dropdown with radio button which needs to show when I click field and hide when I click outside and get the selected value in the inputfield. I have partially working code.
I am not able to hide the dropdown, once it got opened.
I need the selected value in the input field instead of placeholder value which I have.
I see lot of answer's for the select option dropdown but not for the tag placeholder.
//Not sure why the above function is not hiding the dropdown
RadioDdOnclick() {
var x=document.getElementById("radiobtn");
if (x.style.display==="none") {
document.getElementById('RadioDd').style.visibility='hidden'; //i tried style.display ='none';
}
else {
document.getElementById('RadioDd').style.display='block';
}
}
<div className="inputWithIcon" onClick={this.RadioDdOnclick} id="radiobtn">
<input className="inputBlock" id="radioSelect" type="text" placeholder="choose one" />
<i className="fa fa-angle-down" />
</div>
<div className={ "BudgetRadioDd"} id={ "RadioDd"} style={{display: 'none'}}>
<fieldset>
<h4>options to choose</h4>
<div>
<label><input type="radio" id="1"/>option 1</label>
</div>
<div>
<label> <input type="radio" id="2" />option 2</label>
</div>
<div>
<label><input type="radio" id="3"/>option 3</label>
</div>
</fieldset>
</div>
//css code here
.input[type=text]{
width:100%;
border:2px solid #aaa;
border-radius:4px;
margin:8px 0;
outline:none;
padding:8px;
box-sizing:border-box;
transition:.3s;
}
.inputWithIcon{
position:relative;
}
.inputWithIcon i{
position:absolute;
right: 3%;
top: 0;
font-size: 25px;
padding: 20px 8px;
color:#c69937;
transition:.3s;
}
update
Below answer is working but it is rendering the radio value in another div component.
Looking for better solution..
adding the link to look at the issue: https://stackblitz.com/edit/react-feubq6?file=index.js
I updated your code and simplified it to HTML for simplicity. Please check:
function RadioDdOnclick(event) {
const hovered = document.querySelectorAll(':hover');
if (hovered[hovered.length - 1].type !== 'radio') {
const x = document.querySelector('#RadioDd');
const toggleMap = {
none: 'block',
block: 'none'
};
x.style.display = toggleMap[x.style.display];
}
}
document.querySelectorAll('[type=radio]').forEach(r => {
r.onclick = _ => {
if (r.checked) {
document.querySelector('#radioSelect').value = r.value;
}
document.querySelector('#RadioDd').style.display = 'none';
}
});
<div class="inputWithIcon" id="radiobtn">
<input className="inputBlock"
id="radioSelect"
type="text"
onClick="RadioDdOnclick(event)"
onBlur="RadioDdOnclick(event)"
placeholder="choose one" />
<i className="fa fa-angle-down" />
</div>
<div class="BudgetRadioDd" id="RadioDd" style="display: none">
<fieldset>
<h4>options to choose</h4>
<div>
<label>
<input name="budget" type="radio" id="1" value="option 1"/>
option 1
</label>
</div>
<div>
<label>
<input name="budget" type="radio" id="2" value="option 2"/>
option 2
</label>
</div>
<div>
<label>
<input name="budget" type="radio" id="3" value="option 3"/>
option 3
</label>
</div>
</fieldset>
</div>

MySQLi - JS - drop down multi select

beginner here.
Made a drop down where you can select 3 options that i would have placed in my 3 place holders in my database.
In other words, i have 3 attribute records "at1. at2, at3" and a drop down of attributes, like "Red, Blue, Black, Orange, Green" (in the code below, for the moment i just labeled them "one, two, three") that i want placed into at1, at2, at3.
So.. so far i have..
$at0 = $_POST['at0'];
$at1 = $_POST['at1'];
$at2 = $_POST['at2'];
And
<style>
.multiselect {
width: 200px;
}
.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;
}
</style>
Attributes:
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Select an option</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<input type="checkbox" name="at0" id="one" /> one
<label for="two"><input type="checkbox" name="two" id="two" />two
<label for="three"><input type="checkbox" name="three" id="three" />three
</div>
</div>
<script>
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;
}
}
</script>
Is there an easier/cleaner way to have a user select multiple options which all get put in my database?
At the moment it kind of works, when i click on the first checkbox, the word "On" is left in 'at1' in my database.. How do i get what i want to achieve?
As specified in https://developer.mozilla.org/es/docs/Web/HTML/Elemento/input/checkbox
The input checkbox will pass the default "on" if checked.
You can pass a custom value using:
<input type="checkbox" name="at0" id="one" value="mycustomvalue" />
That will make the POST or GET (depending on your form) var "at0" to receive the value "mycustomvalue" if the checkbox is checked.
EDIT:
If you want multiple checkboxes that may or not be checked you can use the array syntax for the name. That is:
HTML:
<input type="checkbox" name="at0[]" id="one" value="valueone" />
<input type="checkbox" name="at0[]" id="two" value="valuetwo" />
<input type="checkbox" name="at0[]" id="three" value="valuethree" />
<input type="checkbox" name="at0[]" id="four" value="valuefour" />
If you check boxes 1 and 3, the PHP part will be
PHP:
echo $_POST["at0"][0]; // will echo "valueone";
echo $_POST["at0"][1]; // will echo "valuethree";
Then it's matter of you how you save that into the DB. Just remember to sanitize your inputs to avoid SQL Injection Attacks

Categories

Resources