Show selected checkbox values using javascript - javascript

I have been trying to create checkboxes and show their values.
When you try to select only one of them, it works.
When you try to select more than one, it only shows the highest value selected.
I want to do this only with javascript, no jquery.
How can I show all the values of all selected checkboxes?
Here is the code so far:
Html:
<!doctype html>
<html>
<head>
<title>Javascript checkboxes in real time</title>
<link rel = "stylesheet" href = "css/default.css">
</head>
<body>
<form action = "" method = "post">
<input type="checkbox" id = "1" value = "1">1<br>
<input type="checkbox" id = "2" value = "2">2<br>
<input type="checkbox" id = "3" value = "3">3<br>
<input type="checkbox" id = "4" value = "4">4<br>
<input type="checkbox" id = "5" value = "5">5<br>
</form>
<section></section>
<script src = "js/default.js"></script>
</body>
</html>
Javascript:
var checkbox = document.getElementsByTagName('input');
var section = document.getElementsByTagName('section');
setInterval(function(){
for(var i = 0; i <= checkbox.length - 1; i++){
if(checkbox[i].checked){
section[0].innerHTML = checkbox[i].value;
break;
}
else{
section[0].innerHTML = null;
}
}
}, 10);

There are several things wrong about your code, you are endlessly querying the DOM every 10ms for no good reason. DOM elements fire events when things happen to them.
var section = document.getElementsByTagName('section')[0];
var inputs = document.getElementsByTagName('input');
// Document was changed!
document.addEventListener('change', function(event) {
// Specifically, an input was changed in the document!
if (event.target.tagName === 'INPUT') {
// Update the section
updateCheckboxStatus(section);
}
});
// This function updates an element with the input status
function updateCheckboxStatus(element) {
// Clear the element first
element.textContent = '';
// Loop through each of the inputs
[].forEach.call(inputs, function(input) {
// If checked, add to the element
if (input.checked) { element.textContent += input.value + " "; }
});
}
<form action="" method="post">
<input type="checkbox" id="1" value="1">1
<br>
<input type="checkbox" id="2" value="2">2
<br>
<input type="checkbox" id="3" value="3">3
<br>
<input type="checkbox" id="4" value="4">4
<br>
<input type="checkbox" id="5" value="5">5
<br>
</form>
<section></section>

EDIT: I'm posting the minimal change I found to fix your issue. This is by no means the right approach to the task at hand - as explained perfectly at the (now) accepted answer. This code should serve just so you'll see the diff from your code.
Also - please don't use setInterval (use setTimeout instead and renew it each time from inside the callback):
var checkbox = document.getElementsByTagName('input');
var section = document.getElementsByTagName('section');
setInterval(function(){
section[0].innerHTML = '';
for(var i = 0; i < checkbox.length; i++){
if(checkbox[i].checked){
section[0].innerHTML += checkbox[i].value;
}
}
}, 10);

Related

JavaScript - add selected array variable to html Form Input tag

By clicking on the button onclick="nextText()" I am able to select and display the next element in the myText array. This shows up in div id="target". I'll like to use input tag - input id="target" value="" so that I can submit the selected element to a database with a form but selected element does not show up in input field. I'm a newbie, is there a way to do this?
var target = document.getElementById('target');
var counter = 0;
var myText = [
"Orange",
"Avocados",
"Banana",
"Berry",
"Apple"
];
function nextText() {
counter += 1;
if (counter > myText.length - 1) {
counter = 0;
}
target.innerHTML = myText[counter];
}
<div>
<div id="target">Fruits</div>
</div>
<input type="button" onclick="nextText()" value="change Text" />
For fun I changed your array to a <datalist> (so, the user can choose either to press the button or start writing in the input an get suggestions), but it has the same kind of functionality - you ca see the function that you made is just part of an event listener.
So, to answer your question: To change the value of <input>, assign the value to .value (here e.target.form.fruits.value).
var counter = 0;
document.forms.form01.change.addEventListener('click', e => {
counter++;
if (counter > e.target.form.fruits.list.children.length - 1) {
counter = 0;
}
e.target.form.fruits.value = e.target.form.fruits.list.children[counter].value;
});
/*this submit event listener is just for testing
depending on your use case, do something else...*/
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
let formData = new FormData(e.target);
console.log([...formData.values()]);
});
<div>
<div id="target">Fruits</div>
</div>
<form name="form01">
<input list="fruitsList" name="fruits" />
<datalist name="fruitsList" id="fruitsList">
<option value="Orange">
<option value="Avocados">
<option value="Banana">
<option value="Berry">
<option value="Apple">
</datalist>
<input name="change" type="button" value="change Text" />
<button>Submit</button>
</form>

JavaScript Array need to display many hidden fields

Fiddle link here
<script>
function show1() {
if (document.getElementById("check1").checked == true) {
document.getElementById("info1").style.display="inline";
} else {
if (document.getElementById("check1").checked == false)
document.getElementById("info1").style.display="none";
}
}
</script>
<input type="checkbox" id="check1" name="check1" value="" onclick="show1();">
<style>
#info1, #info2 {
display: none;
}
</style>
What I need to do about 20 times is to show hidden fields info1, info2 etc. when check1, check2 is selected.
First it is always a good idea to find handlers in Javascript instead of inline events.
Second give all your inputs the same class to do so.
Have a data-* attribute that will store the corresponding input message.
You HTML would look like
HTML
<div class="container">
<div>
<input type="checkbox" id="check1" name="check1" value="" data-id="info1" class="checkbox"/>
<label for="check1">Click here for more information</label>
</div>
<div id="info1" class="info">Hidden information here will now appear onclick check1</div>
</div>
<div class="container">
<div>
<input type="checkbox" id="check2" name="check3" value="" data-id="info2" class="checkbox"/>
<label for="check2">Click here for more information</label>
</div>
<div id="info2" class="info">Hidden information here will now appear onclick check2</div>
</div>
<div class="container">
<div>
<input type="checkbox" id="check3" name="check3" value="" data-id="info3" class="checkbox"/>
<label for="check3">Click here for more information</label>
</div>
<div id="info3" class="info">Hidden information here will now appear onclick check3</div>
</div>
JS
// Get all the checkbox elements
var elems = document.getElementsByClassName('checkbox');
// iterate over and bind the event
for(var i=0; i< elems.length; i++) {
elems[i].addEventListener('change', show);
}
function show() {
// this corresponds to the element in there
// Get the info attribute id
var infoId = this.getAttribute('data-id');
if (this.checked) {
document.getElementById(infoId).style.display = "inline";
} else {
document.getElementById(infoId).style.display = "none";
}
}
Check Fiddle
This is one way of doing this.
I've updated your jsfiddle:
document.addEventListener('change', function(e) {
var id = e.target.getAttribute('data-info-id');
var checked = e.target.checked;
if (id) {
var div = document.getElementById(id);
if (div) div.style.display = checked ? 'block' : 'none';
}
});
Instead of creating an if ... else block for every checkbox, which becomes hard to maintain, I've associated every check with its DIV via the custom attribute data-info-id, which is set to the id of the aforementioned DIV.
I bind the 'change' event to the document (event delegation) and when it fires I check the source element has a data-info-id attribute. Then, I get the DIV with such id and show or hide it based on the value of the checked property.
The obvious advantage of doing it this way, via custom attributes, is that you don't depend of the position of the div, and you can change which checks shows what DIV in a declarative way, just changing the HTML.
Maybe you are looking for a javascript only solution, but there's a pretty simple solution in CSS
HTML
<div>
<input type="checkbox" id="check1" name="check1" value="" />
<label for="check1"> Click here for more information</label>
<div id="info1">Hidden information here will now appear onclick </div>
</div>
<div>
<input type="checkbox" id="check2" name="check2" value=""/>
<label for="check2"> Click here for more information</label>
<div id="info2">Hidden information here will now appear onclick </div>
</div>
CSS
input[type=checkbox] ~ div {
display: none;
}
input[type=checkbox]:checked ~ div {
display: block;
}
Fiddle here
Looks for an input with the data-enable attribute that matches to the id of the element being shown/hidden.
HTML
<input type="checkbox" data-enable="info0" name="check[]"/>
<input type="text" id="info0" name="info[]"/>
Javascript
function toggleEl(evt) {
var checkbox = evt.target;
var target = checkbox.getAttribute('data-enable');
var targetEl = document.getElementById(target);
// if checked, use backed-up type; otherwise hide
targetEl.type = (checkbox.checked)
? targetEl.getAttribute('data-type')
: 'hidden';
}
var inputs = document.getElementsByTagName('input');
for(var i=0,l=inputs.length;i<l;i++) {
var input = inputs[i];
var target = input.getAttribute('data-enable');
if(target!==null) {
var targetEl = document.getElementById(target);
// back-up type
targetEl.setAttribute('data-type',targetEl.type);
// hide it if the checkbox is not checked by default
if(!input.checked)
{ targetEl.type = 'hidden'; }
// add behavior
input.addEventListener('change',toggleEl,false);
}
}
Check out the following JSFiddle .
//<![CDATA[
// common.js
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function gteIE(version, className){
if(IE >= version)bod.className = className;
}
function E(e){
return doc.getElementById(e);
}
//]]>
//<![CDATA[
// adjust numbers as needed
for(var i=1; i<2; i++){
(function(i){
E('check'+i).onclick = function(){
var a = E('info'+i).style.display = this.checked ? 'block' : 'none';
}
})(i);
}
//]]>

How can I disable the submit button?

Here is the code How can I disable the submit button. It doesn't appear to be working for us.I want to be able to have the button disabled when the page is brought up. Do you have any ideas on how we can fix this?
// Script 10.5 - pizza.js
// This script creates a master checkbox.
// Function called when the checkbox's value changes.
// Function toggles all the other checkboxes.
function toggleCheckboxes() {
'use strict';
// Get the master checkbox's value:
var status = document.getElementById('toggle').checked;
// Get all the checkboxes:
var boxes = document.querySelectorAll('input[type="checkbox"]');
// Loop through the checkboxes, starting with the second:
for (var i = 1, count = boxes.length; i < count; i++) {
// Update the checked property:
boxes[i].checked = status;
} // End of FOR loop.
}
} // End of toggleCheckboxes() function.
function disabled () {
if ('')
{document.getElementById('submit').disabled = false;}
else
{document.getElementById('submit').disabled = true;}
// Establish functionality on window load:
window.onload = function() {
'use strict';
// Add an event handler to the master checkbox:
document.getElementById('toggle').onchange = toggleCheckboxes;
document.getElementById('submit').disabled = disabled;
};
Here is the html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Operating Systems</title>
<!--[if lt IE 9]>
<script </script>
<![endif]-->
</head>
<body>
<!-- Script 10.4 - pizza.html -->
<form action="#" method="post" id="theForm">
<fieldset><legend>Create Your Own Pizza</legend>
<div><label>Toppings</label> <input type="checkbox" name="toggle" id="toggle" value="toggle"> All/None
<p><input type="checkbox" name="ham" id="ham" value="ham"> Ham
<input type="checkbox" name="mushrooms" id="mushrooms" value="mushrooms"> Mushrooms
<input type="checkbox" name="onions" id="onions" value="onions"> Onions
<input type="checkbox" name="sausage" id="sausage" value="sausage"> Sausage
<input type="checkbox" name="greenPeppers" id="greenPeppers" value="greenPeppers"> Green Peppers </p>
</div>
<input type="checkbox" name="terms" id="terms" required> I agree to the terms, whatever they are.
<input type="submit" name="submit" value="Submit" id="submit">
</fieldset>
<div id="output"></div>
</form>
<script src="js/utilities.js"></script>
<script src="js/pizza.js"></script>
<script src="js/modal.js"></script>
</body>
</html>
There are a few things that could be improved:
You should close all your input tags to avoid any issues rendering the HTML document.
The for-loop should run until i < (boxes.length - 1) to avoid selecting the ToS checkbox. Or you could target just the toppings with querySelectorAll('p input[type="checkbox"]') and start from var i = 0.
The closing bracket for disable() is between the closing brackets for the for-loop andtoggleCheckboxes().
In disabled() #terms is selected, you want to check if it is checked or not. If it is, enable the submit button (disabled = false), else disable it (disabled = true).
Finally, you'll want to assign disabled() to the #terms' onclick function so it is called every time the checkbox is toggled.
Demo: http://jsfiddle.net/4Rwfs/1
HTML
<form action="#" method="post" id="theForm">
<fieldset>
<legend>Create Your Own Pizza</legend>
<div>
<label>Toppings</label>
<input type="checkbox" name="toggle" id="toggle" value="toggle">All/None</input>
<p>
<input type="checkbox" name="ham" id="ham" value="ham">Ham</input>
<input type="checkbox" name="mushrooms" id="mushrooms" value="mushrooms">Mushrooms</input>
<input type="checkbox" name="onions" id="onions" value="onions">Onions</input>
<input type="checkbox" name="sausage" id="sausage" value="sausage">Sausage</input>
<input type="checkbox" name="greenPeppers" id="greenPeppers" value="greenPeppers">Green Peppers</input>
</p>
</div>
<input type="checkbox" name="terms" id="terms" required> I agree to the terms, whatever they are.</input>
<input type="submit" name="submit" value="Submit" id="submit"></input>
</fieldset>
<div id="output"></div>
</form>
JavaScript
// Script 10.5 - pizza.js
// This script creates a master checkbox.
// Function called when the checkbox's value changes.
// Function toggles all the other checkboxes.
function toggleCheckboxes() {
'use strict';
// Get the master checkbox's value:
var status = document.getElementById('toggle').checked;
// Get all the checkboxes:
var boxes = document.querySelectorAll('p input[type="checkbox"]');
// Loop through the checkboxes, starting with the second:
for (var i = 0, count = boxes.length; i < count; i++) {
// Update the checked property:
boxes[i].checked = status;
} // End of FOR loop.
} // End of toggleCheckboxes() function.
function disabled () {
if (document.getElementById('terms').checked)
{document.getElementById('submit').disabled = false;}
else
{document.getElementById('submit').disabled = true;}
}
// Establish functionality on window load:
window.onload = function() {
'use strict';
// Add an event handler to the master checkbox:
document.getElementById('toggle').onchange = toggleCheckboxes;
document.getElementById('submit').disabled = true;
document.getElementById('terms').onchange = disabled;
};
If you want to disable the submit button on page load, try adding this:
document.getElementById('submit').disabled = true;
The following line doesn't make sense unless the disabled function returns a boolean:
document.getElementById('submit').disabled = disabled;
For example, this would work if you wanted the submit button to disable on click.
document.getElementById('submit').onclick = disabled;
The problem is not in the disable line.
What did you trying to do with if('') { ? Also, in your onload function, there is a line :
'use strict';
What are you trying to do again?
See : http://jsfiddle.net/ByKEJ/
How to disable html button using JavaScript?
I think this previous solution can help you dynamically disable something

How to know which radio is checked from a fieldset

I have the following code:
<fieldset id="dificuldade">
<legend>Dificuldade:</legend>
<input type="radio" name="dificuldade" value="facil"> Fácil </input>
<input type="radio" name="dificuldade" value="medio"> Médio </input>
<input type="radio" name="dificuldade" value="dificil"> Difícil </input>
</fieldset>
<fieldset id="tipo">
<legend>Tipo de jogo:</legend>
<input type="radio" name="Tipodejogo" value="somar"> Somar </input>
<input type="radio" name="Tipodejogo" value="subtrair"> Subtrair </input>
<input type="radio" name="Tipodejogo" value="dividir"> Dividir </input>
<input type="radio" name="Tipodejogo" value="multiplicar"> Multiplicar </input>
</fieldset>
<input type="button" value="Começa" id="button" ></input>
</form>
and here is the jsfiddle with both the html and the js http://jsfiddle.net/3bc9m/15/ . I need to store the values of the 2 fieldset so I, depending on the values picked can generate a game, but my javascript isn't returning any of them. What is wrong? I've been told that JQuery is much easier but i can't use it.
Your code on jsFiddle seems to be working fine for the most part. The only thing was that the elements output and output2 don't exist on the page.
So this code that was supposed to display the selected values wasn't working:
document.getElementById('output').innerHTML = curr.value;
document.getElementById('output2').innerHTML = tdj.value;
The part that actually retrieves the selected values is working fine.
Just add those two elements to the page, like this:
<p>Selected Values:</p>
<div id="output"></div>
<div id="output2"></div>
An updated jsFiddle can be found here.
EDIT
If a radio button from only one of the sets is selected, the code fails. You could use this code to find the selected values instead:
document.getElementById('button').onclick = function() {
var dif = document.getElementsByName('dificuldade');
var tip = document.getElementsByName('Tipodejogo');
var difValue;
for (var i = 0; i < dif.length; i++) {
if (dif[i].type === "radio" && dif[i].checked) {
difValue = dif[i].value;
}
}
var tipValue;
for (var i = 0; i < tip.length; i++) {
if (tip[i].type === "radio" && tip[i].checked) {
tipValue = tip[i].value;
}
}
document.getElementById('output').innerHTML = difValue;
document.getElementById('output2').innerHTML = tipValue;
};​
An updated jsFiddle is here.
Consider this post that adresses the issue. It shows a few javascript methods as well as how you would use it in jQuery.
How can I check whether a radio button is selected with JavaScript?
Is there a specific reason you want to break it down by fieldset instead of directly accessing the radio buttons by name?

How to get all elements which name starts with some string?

I have an HTML page. I would like to extract all elements whose name starts with "q1_".
How can I achieve this in JavaScript?
A quick and easy way is to use jQuery and do this:
var $eles = $(":input[name^='q1_']").css("color","yellow");
That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:
var DOMeles = $eles.get();
see http://api.jquery.com/attribute-starts-with-selector/
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'q1_' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('q1_') == 0) {
eles.push(inputs[i]);
}
}
HTML DOM querySelectorAll() method seems apt here.
W3School Link given here
Syntax (As given in W3School)
document.querySelectorAll(CSS selectors)
So the answer.
document.querySelectorAll("[name^=q1_]")
Fiddle
Edit:
Considering FLX's suggestion adding link to MDN here
You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input name="q1_a" type="text" value="1A"/>
<input name="q1_b" type="text" value="1B"/>
<input name="q1_c" type="text" value="1C"/>
<input name="q2_d" type="text" value="2D"/>
<script type="text/javascript">
var inputs = document.getElementsByTagName("input");
for (x = 0 ; x < inputs.length ; x++){
myname = inputs[x].getAttribute("name");
if(myname.indexOf("q1_")==0){
alert(myname);
// do more stuff here
}
}
</script>
</body>
</html>
Demo
Using pure java-script, here is a working code example
<input type="checkbox" name="fruit1" checked/>
<input type="checkbox" name="fruit2" checked />
<input type="checkbox" name="fruit3" checked />
<input type="checkbox" name="other1" checked />
<input type="checkbox" name="other2" checked />
<br>
<input type="button" name="check" value="count checked checkboxes name starts with fruit*" onClick="checkboxes();" />
<script>
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true &&
inputElems[i].name.indexOf('fruit') == 0)
{
count++;
}
}
alert(count);
}
</script>
You can try using jQuery with the Attribute Contains Prefix Selector.
$('[id|=q1_]')
Haven't tested it though.

Categories

Resources