I've got an array of checkboxes I need to display to the user the options they select to provide a total price for those options. The issue is that when I run the code I don't get any value in the array and I'm not sure why because I've correctly referenced the checkboxes. I've tried fixing the number of iterations in the for loop and renaming variables but I cant seem to get it to work.
var checkbox_list = document.forms[0];
var txt = "";
var checkedValue = null;
var inputElements = document.getElementsByClassName("checkboxb");
for (var i = 0; inputElements[i]; i++) {
if (inputElements[i].checked) {
txt += checkbox_list[i].value + ", ";
alert(txt);
break;
}
}
document.getElementById("quote").innerText = txt + "";
<div id="checkboxes">
<label for="one"><input type="checkbox" class="checkboxb"
name="options1"/>First checkbox</label>
<label for="two"><input type="checkbox" class="checkboxb"
name="options2"/>Second checkbox</label>
<label for="three"><input type="checkbox" class="checkboxb"
name="options3"/>Third checkbox</label>
</div>
You may also want an ES6 approach.
// This line just stores the inputs
const inputElements = document.getElementsByClassName("checkboxb");
// This replaces your for-loop. It iterates through the inputs and if they are checked,
// add the current value to an accumulated value
const calculate = _ => [...inputElements].reduce((a, c) => c.checked ? (a + ", " + c.value) : a, "").substr(2);
// This just performs the calculation whenever checkbox change, and display that result
[...inputElements].forEach(x => x.addEventListener("change", _ => quote.innerText = calculate()));
<div id="checkboxes">
<label><input type="checkbox" class="checkboxb"
name="options1" value="one"/>First checkbox</label>
<label><input type="checkbox" class="checkboxb"
name="options2" value="two"/>Second checkbox</label>
<label><input type="checkbox" class="checkboxb"
name="options3" value="three"/>Third checkbox</label>
</div>
<div id="quote"></div>
Related
So I got a project here with a couple of radiobuttons. The plan is to be able to select a base, a lining, color and a shading technique. The blue box to the right serves the purpose of giving the customer a live overview of example outcome of the selected parts. I want to place an image there, with a variable URL.
My plan would be to do something like: "https://www.example.com/images/calculator/base+line+color+shading.png"
Where base is gotten from the base radio input, and could be for example "fullbody"Where line is gotten from the line radio input, and could be for example "clean"Where color is gotten from the color radio input, and could be for example "colored"Where shading is gotten from the shading radio input, and could be for example "ccel"This would leave us with a variable url of "https://www.example.com/images/calculator/fullbody+clean+colored+ccel.png"
At the same time, I don't want them to have to select all of the inputs to get an overview, if they only select "fullbody", the variable URL should become "https://www.example.com/images/calculator/fullbody.png"
The artist I'm doing this for is rapidly increasing the product base and style choices, and I will be updating it over time, so a solution that is expandable with more options over time would be amazing.
As always, thank you for taking your time to read over, any answers or tips/tricks/hints or pointing in directions is greatly appreciated! Enjoy the weekend folks! <3
small overview of my project layout
data-position="1" is for base group
data-position="2" is for line group
data-position="3" is for color group
data-position="4" is for shade group
..
..
data-position="k" will be for kth value group and so on...
See working example here https://jsfiddle.net/y2khfjwp/40/
<div style="width: 50%; float: Left;">
<h2>
Base
</h2>
<input type="radio" name="base" class="main-inputs" data-position="1" value="fullbody" onchange="makeImage(this)"/>Full Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="halfbody" onchange="makeImage(this)"/>Half Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="xyzbody" onchange="makeImage(this)"/>xyz Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="abcbody" onchange="makeImage(this)"/>abc body<br>
<hr>
<h2>
Line
</h2>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean" onchange="makeImage(this)"/>Clean<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean2" onchange="makeImage(this)"/>Clean2<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean3" onchange="makeImage(this)"/>Clean3<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean4" onchange="makeImage(this)"/>Clean4<br>
<hr>
<h2>
Color
</h2>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored" onchange="makeImage(this)"/>Colored<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored2" onchange="makeImage(this)"/>Colored2<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored3" onchange="makeImage(this)"/>Colored3<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored4" onchange="makeImage(this)"/>Colored4<br>
<hr>
<h2>
Shade
</h2>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel" onchange="makeImage(this)"/>Ccel<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel2" onchange="makeImage(this)"/>Ccel2<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel3" onchange="makeImage(this)"/>Ccel3<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel4" onchange="makeImage(this)"/>Ccel4<br>
</div>
<div style="width: 50%; float: Right;">
OutPut: <img id="final-output-src" src="Please select Options" /><br><span id="final-output">Please select Options</span>
</div>
<script>
var path = [];
function makeImage(element)
{
var imagePath = "";
path[element.getAttribute('data-position')] = element.value;
imagePath = finalImagePath();
document.getElementById("final-output-src").src = imagePath;
document.getElementById("final-output").innerHTML = imagePath;
};
function finalImagePath() {
var imageSrc = "https://www.example.com/images/calculator/";
var selections = "";
for(var i=1 ; i<=path.length ; i++) {
if(typeof path[i] != 'undefined' && path[i] != '') {
if(selections == "") {
selections = selections + path[i];
} else {
selections = selections + "+" + path[i];
}
}
}
if(selections != "") {
selections = selections + ".png";
imageSrc = imageSrc + selections;
}
return imageSrc;
}
</script>
Okay here is a solution to generate the image url:
const partials = document.querySelectorAll('#partials input');
const fullBody = document.getElementById('fullbody');
const baseUrl = 'some-root-url.com/';
const fileType = '.png';
let imageUrl = baseUrl + 'some-default-url' + fileType;
// Add Event Listeners
fullBody.addEventListener('change', function(){
let checked = document.querySelectorAll('#partials input:checked');
// deselect each partial
for(let i = 0; i < checked.length; i++){
checked[i].checked = false;
}
// Set the imageUrl var to the fullbody
imageUrl = baseUrl + this.value + fileType;
// see the imageUrl!
console.log(imageUrl);
});
for(let i = 0; i < partials.length; i++){
partials[i].addEventListener('change', function(){
// uncheck fullBody if checked
fullBody.checked = false;
// init the imageUrl
imageUrl = baseUrl;
// loop through each checked option and add the value to the imageUrl
let checked = document.querySelectorAll('#partials input:checked');
for(let i = 0; i < checked.length; i++){
imageUrl += checked[i].value;
}
// add the file type
imageUrl += fileType;
// see the imageUrl!
console.log(imageUrl)
});
}
And here's the corresponding HTML
<div id="partials">
<label for="base">Base</label><input name="base" type="checkbox" value="base" /><br />
<label for="line">Line</label><input name="line" type="checkbox" value="line" /><br />
<label for="color">Color</label><input name="color" type="checkbox" value="color" /><br />
<label for="Shading">Shading</label><input name="shading" type="checkbox" value="shading" />
</div>
<label for="fullbody">Full Body</label><input name="fullbody" id="fullbody" type="checkbox" value="fullbody" />
And a JSFiddle to demo
One tip for you as well, you want to use checkboxes not radio, as radio are designed for single choices not multiselect.
Hope that helps!
when checkbox are checked for each checkbox jquery create input
How can I get all inputs with name??
if checkbox checked create input:
<script>
function dynInput(cbox) {
if (cbox.checked) {
var input = document.createElement("input");
input.type = "text";
input.className = "cbox";
var div = document.createElement("div");
div.className = "cbox-div";
div.id = cbox.name;
div.innerHTML =cbox.name;
div.appendChild(input);
document.getElementById("insertinputs").appendChild(div);
} else {
document.getElementById(cbox.name).remove();
}
}</script>
checkbox and Inputs:
<form class="add-item">
<input type="checkbox" onclick="dynInput(this);" name="1"> 1<br>
<input type="checkbox" onclick="dynInput(this);" name="2"> 2<br>
<input type="checkbox" onclick="dynInput(this);" name="3"> 3<br>
<input type="checkbox" onclick="dynInput(this);" name="4"> 4<br>
</form>
<p id="insertinputs"></p>
I can only get first Input value :
var item = $(".cbox").val();
console.log(item);
You need to iterate over all the inputs like:
$(".cbox").each(function(){
var item = $(this).val();
console.log(item);
});
var item=[];
$(".cbox").each(function(){
item.push($(this).val());
});
var items = document.querySelectorAll('.cbox');
var values = [];
items.forEach(function(item) {
values.push(item.value);
});
console.log(values);
because as the documentation states for val() it only returns the first item in the collection. You would need to loop over the collection and read each item's value.
So you need to loop over the collection and build up the list. You can do it with each() or map()
var vals1 = [];
$('[type="checkbox"]').each( function () {
vals1.push(this.value);
});
var vals2 = $('[type="checkbox"]').map( function () {
return this.value;
}).get();
console.log("vals1", vals1.join(","))
console.log("vals2", vals2.join(","))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="a"> 1<br>
<input type="checkbox" value="b"> 2<br>
Im trying to loop over an array to create some form tags, depending on how many values there are in the array. So far i have got my label and input tags that are being created. The problem i am having is displaying the input tags correctly after the labels. Any help would be much appreciated!
I'm trying to achieve:
<label class="material-label" for="leather_materials">
<input id="leather_materials" class="shoe-materials" type="radio" name="materials" value="leather">
<label class="material-label" for="suade_materials">
<input id="suade_materials" class="shoe-materials" type="radio" name="materials" value="suade">
<label class="material-label" for="nubuck_materials">
<input id="nubuck_materials" class="shoe-materials" type="radio" name="materials" value="nubuck">
my code so far:
materialArray = ['leather','suade','nubuck'];
//loop over material array
for( i = 0; i < materialArray.length; i++) {
//create label elements
var matLabel = document.createElement('label');
matLabel.setAttribute('for', materialArray[i] + '_materials');
matLabel.setAttribute('class', 'material-label');
console.log(matLabel);
//add text to label elements
var matLabelTextNode = document.createTextNode(materialArray[i]);
matLabel.appendChild(matLabelTextNode);
//create input elements
var matInput = document.createElement('input');
matInput.className = 'shoe-materials';
matInput.setAttribute('class', 'shoe-materials');
matInput.setAttribute('id', materialArray[i] +'_materials');
matInput.setAttribute('name', 'materials');
matInput.setAttribute('type', 'radio');
matInput.setAttribute('value', materialArray[i]);
console.log(matInput);
//append to parent div
addMaterials.appendChild(matLabel);
$('.material-label').after(matInput);
}
I tried using jQuery after() but it went a bit messed up and got the following
<label class="material-label" for="leather_materials">leather</label>
<input id="nubuck_materials" class="shoe-materials" type="radio" name="materials" value="nubuck">
<input id="suade_materials" class="shoe-materials" type="radio" name="materials" value="suade">
<input id="leather_materials" class="shoe-materials" type="radio" name="materials" value="leather">
<label class="material-label" for="suade_materials">suade</label>
<input id="nubuck_materials" class="shoe-materials" type="radio" name="materials" value="nubuck">
<input id="suade_materials" class="shoe-materials" type="radio" name="materials" value="suade">
<label class="material-label" for="nubuck_materials">nubuck</label>
<input id="nubuck_materials" class="shoe-materials" type="radio" name="materials" value="nubuck">
Mistake you're doing is appending those elements after the .material-label element. So you keep adding them after the labels which has already that class.
From :
$('.material-label').after(matInput);
To:
$(matLabel).after(matInput);
Updated code:
var addMaterials = document.getElementById("addMaterials");
materialArray = ['leather','suade','nubuck'];
//loop over material array
for( i = 0; i < materialArray.length; i++) {
//create label elements
var matLabel = document.createElement('label');
matLabel.setAttribute('for', materialArray[i] + '_materials');
matLabel.setAttribute('class', 'material-label');
console.log(matLabel);
//add text to label elements
var matLabelTextNode = document.createTextNode(materialArray[i]);
matLabel.appendChild(matLabelTextNode);
//create input elements
var matInput = document.createElement('input');
matInput.className = 'shoe-materials';
matInput.setAttribute('class', 'shoe-materials');
matInput.setAttribute('id', materialArray[i] +'_materials');
matInput.setAttribute('name', 'materials');
matInput.setAttribute('type', 'radio');
matInput.setAttribute('value', materialArray[i]);
console.log(matInput);
//append to parent div
addMaterials.appendChild(matLabel);
$(matLabel).after(matInput);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addMaterials"></div>
The jQuery statement $('.material-label') selects every element with that class, so when you use $('.material-label').after(matInput), you are adding the contents of matInput after each of the three labels.
To get the current label, just use i as the index for the array returned by $('.material-label').
Changing
//append to parent div
addMaterials.appendChild(matLabel);
$('.material-label').after(matInput);
To
//append to parent div
currentLabel = $('.material-label')[i];
$(currentLabel).after(matInput);
Will get the results you want.
Change '.material-label' to matLabel
$(matLabel).after(matInput);
Here is the JSFiddle: https://jsfiddle.net/82o6hfna/
I never liked the object manipulation approach to building html. I like to build the string of html then insert it into the dom. Just my opinion.
JS
//to uppercase of first letter only
String.prototype.toUpperCaseFirstLetter = function() {
var s = this;
return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}
var materialArray = ['leather','suade','nubuck'];
function buildMaterialRadios () {
var str = '';
for (var i = 0; i < materialArray.length; i++) {
var item = materialArray[i];
str += '<label class="material-label" for="'+item+'_materials">'+item.toUpperCaseFirstLetter()+'</label><input id="'+item+'_materials" class="shoe-materials" type="radio" name="materials" value="'+item+'">';
};
document.getElementById('material_selections').innerHTML = str;
}
buildMaterialRadios();
HTML
<form name="shoebuilderform">
<div id="material_selections"></div>
</form>
http://jsfiddle.net/qcmdnd4d/
Here's my code:
<script type="text/javascript" xml:space="preserve">
function ATHD(f) {
var aa = "I would like help with the following topic(s): "
var bb = "Password Reset "
var cc = "Password Setup "
var dd = "Firmware Upgrade (if applicable) "
var ee = "Local Access Setup "
var ff = "Remote Access Setup "
var gg = "Mobile Access Setup "
var hh = "Recording Schedule Setup "
var ii = "How to playback video "
var jj = "How to convert video "
var kk = "Email Notification Setup "
var ll = "PTZ Setup (if applicable) "
if( f.pr.checked == true) {
f.sup.value = aa + bb;
}
if( f.ps.checked == true) {
f.sup.value = aa + cc;
}
}
</script>
<form><input onclick="ATHD(this.form)" id="1" type="checkbox" name="pr" /> Password Reset<br />
<input onclick="ATHD(this.form)" id="2" type="checkbox" name="ps" /> Password Setup<br />
<input onclick="ATHD(this.form)" id="3" type="checkbox" name="fu" /> Firmware Upgrade (if applicable)<br />
<input onclick="ATHD(this.form)" id="4" type="checkbox" name="la" /> Local Access Setup<br />
<input onclick="ATHD(this.form)" id="5" type="checkbox" name="ra" /> Remote Access Setup<br />
<input onclick="ATHD(this.form)" id="6" type="checkbox" name="ma" /> Mobile Access Setup<br />
<input onclick="ATHD(this.form)" id="7" type="checkbox" name="rss" /> Recording Schedule Setup<br />
<input onclick="ATHD(this.form)" id="8" type="checkbox" name="pb" /> How to playback video<br />
<input onclick="ATHD(this.form)" id="9" type="checkbox" name="cv" /> How to convert video<br />
<input onclick="ATHD(this.form)" id="10" type="checkbox" name="en" /> Email Notification Setup<br />
<input onclick="ATHD(this.form)" id="11" type="checkbox" name="ptz" /> PTZ Setup (if applicable)<br />
<br />
<span style="FONT-WEIGHT: bold">Question</span><span style="COLOR: #ff0000">*</span> (please be specific)<br />
<br />
<textarea style="HEIGHT: 164px; WIDTH: 577px" rows="10" cols="40">
</textarea></p>
<p><button>Continue...</button>
<textarea style="HEIGHT: 164px; DISPLAY: hidden; WIDTH: 577px" rows="10" cols="40" name="sup">
</textarea>
</p>
</form>
Basically, what I am looking to do is to whenever a box is checked, I want the value of the checkbox to be added into a hidden field. I understand that I still need to add the "value=[the value of the checkbox]" in the html code; what I want to allow for is multiple checkboxes to be selected so that multiple items will get added to the textbox.
I understand that one way of doing this would be to be to create if-then statements for every possible variation; this would not be very time effective as there would be thousands of permutations.
I am also trying to figure out if using an array would work to simplify this; I am not really sure how to conceptualize this in the simplest way as I have only been doing javascripting for three weeks. If someone can tell me how to think about this, I would greatly appreciate it. Looking more to learn how to do this so I can contribute to these forums and simplify the process of scripting functions as I do not have a background in coding.
If you can use jQuery, you won't need much code:
You could update the results whenever somebody clicks on a checkbox ($('input').on('click', function() {).
I personally would use <label> elements, but that's just me. You could grab the values by
$('input:checked').each(function() {
values.push($(this).parent().text());
});
Here is a working example: http://jsfiddle.net/HarryPehkonen/zNfju/1/
I have made small changes your dom like removing onclick events and It may solve your problem
var arr = [];
remove_item = function(arr,value){
for(b in arr ){
if(arr[b] == value){
arr.splice(b,1);
break;
}
}
return arr;
}
var inputs = document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if(inputs[i].getAttribute('type') == 'checkbox')
{ inputs[i].addEventListener("change",function() {
if(this.checked)
arr.push(parseInt(this.id));
else
{
remove_item(arr,parseInt(this.id));
}
console.log(arr); document.getElementById("chcbx").value = arr.join(",");
},false);
}
}
and have a look at jsFiddle remove_item
Here's another way of doing it.
// find number of checkboxes (you haven't specified if you
// have a set number or not. If you have a set number, just
// set checkboxCount to whatever number you have.
var checkboxCount = 0;
var inputTags = document.getElementsByTagName('input');
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].getAttribute("name") + ';';
}
document.getElementById("hdnValues").value = totalValue;
alert(totalValue);
}
This basically counts all the checkboxes, loops through all, checks if they're checked, gets the value of the name attribute, then appends it to a string which is delimited by ;
jsfiddle: http://jsfiddle.net/mcDvw/
Alternatively, you could set all the values you want into the value attribute of the checkbox and read that instead of having the value in JS variable. e.g.
HTML:
<input onclick="ATHD()" id="1" type="checkbox" name="pr" value="Password Reset" /> Password Reset<br />
<input onclick="ATHD()" id="2" type="checkbox" name="ps" value="Password Setup" /> Password Setup<br />
JS:
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].value + ';';
}
document.getElementById("hdnValues").value = totalValue;
document.getElementById("showValues").value = totalValue;
}
jsfiddle: http://jsfiddle.net/mcDvw/1/
I need a function that can add checkbox values on click event. My html code is
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<center><b> Plattforms </b></center>
<input type="checkbox" name="cbs" id="cbs" value = 945345 />
<label for="cbs">945345 Symbian</label>
<input type="checkbox" name="cbi" id="cbi" value = 945345 />
<label for="cbi">945345 iPhone</label>
<input type="checkbox" name="cbb" id="cbb" value = 945345 />
<label for="cbb">945345 Blackberry</label>
<input type="checkbox" name="cba" id="cba" value = 945345 />
<label for="cba">945345 Android</label>
<input type="checkbox" name="cbw" id="cbw" value = 945345 />
<label for="cbw">945345 Windows Mobile</label>
<input type="checkbox" name="cbo" id="cbo" value = 945345 />
<label for="cbo">945345 All Other</label>
</fieldset>
</div>
The logic is when a user click on a checkbox, the checkbox value goes to a variable and again the user if clicks on another checkbox that value adds up into first value. Thanks in advance
Do you mean like:
var total = 0;
$("input[type='checkbox']").click(function() {
//if you want to add on checked
if($(this).is(":checked")) {
var v = parseInt($(this).val(), 10);
total += v;
}
else {
total -= v;
}
});
Hope it helps
You could do;
var tot = 0;
$("input:checkbox").click(function() {
var val = parseInt(this.value, 10);
if($(this).is(":checked")) {
//add to total if it's checked
tot += vale;
}else{
//this was previously checked, subtract it's value from total
tot -= vale;
}
});