Buttons with input radio types inserted - javascript

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>

Related

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>

Make radio buttons checked /unchecked

$("input[type='radio']").each(function() {
if ($(this).is(":checked")) {
$(this).css('background', 'blue');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">
My approach is to first check if my inputs are :checked and if they are, put some CSS class with the background color. I achieve that, the next thing I want to is to remove that :checked when users click on radio button or any other (better) idea. After the form is submitted, this code checks if inputs are:checked, the problem is when I want to select another radio button I get something like this:
1 and 2 radio buttons are selected, it should be only 2 :checked
You need to add the else to remove the blue color like :
$("input[type='radio']").each(function () {
if ($(this).is(":checked")) {
$(this).css('background', 'blue');
}else{
$(this).css('background', 'white');
}
});
You could also attach a click event for those radios like :
$("body").on("click", "input[type='radio']", function () {
$("input[type='radio']").css('background', 'white');
$(this).css('background', 'blue');
});
The issue with your JS is that you never remove the class from any of the unselected checkboxes. Also note that each() only runs when the page loads (assuming you've not placed it in an event handler, but the question doesn't show that), so you need to instead run your logic in a change event handler:
var $radio = $("input[type='radio']").on('change', function() {
$radio.removeClass('blue');
$(this).toggleClass('blue', this.checked);
});
That being said, what you're trying to do can be achieved more simply by using CSS:
input {
visibility: hidden;
}
input:before {
content: '';
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #CCC;
visibility: visible;
}
input:checked:before {
background-color: blue;
}
<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">
I think the issue with your code is that you are using each event instead of change or click event. It means that you are trying to change the color of your radio button, even before user has performed any action. Read the following code, this will solve the issue of submitting the form and also customizing the radio button:
$(".radio-button").click(function() {
$(this).addClass("blue-background");
$(this).siblings().removeClass("blue-background");
var radioID = $(this).data('radio');
$('#' + radioID).attr("checked", "checked");
if ($('#' + radioID).siblings(":checked")) {
$('#' + radioID).siblings().removeAttr("checked");
}
});
.blue-background {
background-color: blue;
}
input[type='radio'] {
visibility: hidden;
}
.radio-button {
height: 15px;
width: 15px;
margin: 5px;
border-radius: 50%;
display: inline-block;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<input type="radio" id="radio1" data="cool" name="cool" checked="checked">
<input type="radio" id="radio2" data="cool" name="cool">
<input type="radio" id="radio3" data="cool" name="cool">
<div class="radio-button" data-radio="radio1"></div>
<div class="radio-button" data-radio="radio2"></div>
<div class="radio-button" data-radio="radio3"></div>
</div>
I hope this was helpful.

Show Label of multiple checked checkbox with 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>

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

Changing the state of B by selecting A or C with CSS/HTML/JavaScript

I've a 3 way html/CSS/JavaScript toggle (radio buttons) set up here.
3 options: A / "X" / B Where "X" is none.
HTML
<div class="ABSelector">
<label class="Astate">
A
<input name="state" type="radio" value="A" />
</label>
<label class="nostate">
x
<input name="state" type="radio" value="" checked />
</label>
<label class="Bstate">
B
<input name="state" type="radio" value="B" />
</label>
</div>
Relevant bit of the CSS
label {
cursor: pointer;
display: block;
float: left;
width:40px;
height:40px;
//background-color:green;
line-height:40px;
text-align:center;
}
label.Astate.selected {
background-color:indianred;
color: white;
border-top-left-radius:10px;
border-bottom-left-radius:10px;
}
label.Astate.selected .nostate{
color:grey;
}
label.Bstate.selected {
background-color:orange;
color: white;
border-top-right-radius:10px;
border-bottom-right-radius:10px;
}
label.nostate.selected {
background-color:white;
color: white;
}
Javascript
window.addEvent('domready', function() {
$$('input').set({
events: {
change: function(el) {
$$('label').removeClass('selected');
this.getParent('label').addClass('selected');
}
}
});
});
The JavaScript enables/disables .selected
When the page loads initially the X is visible. Only after the first clicks the X will then only appears if A or B has been clicked. If the X is clicked it disappears.
I'd like to set it so the X only appears when either A or B is clicked. even when the page loads.
Am I missing something on the CSS side or does this need to be solved with JavaScript?
You can just amend your html with this, adding the selected class to your label, making it in fact, invisible:
<label class="nostate selected">
x
<input name="state" type="radio" value="" checked />
</label>
It is happening because of
label.nostate.selected {
background-color: white;
color: white;
it sets color of text to white which is not visible as background in white. Change color of text or its background

Categories

Resources