I've been researching for a few days methods of controlling UI with checkboxes and with the help of some members on Stack' I've come really quite far. But my balding doesn't quite stop yet. I've been trying to further tweak my code snippet, by including a numeric value alongside my UI controller. (This value will be of use later inside the web-java applet.)
For example, when a checkbox is checked var total is ammended from 0 to 30. If a Checkbox is unchecked the value returns to '0'.
(Main Build JS Fiddle),
(Checkbox Example).
The second fiddle allows the use of data attributes, however these will need to be injected into the HTML via, JS. As like before I have 'NO' access to the CSS or HTML source files.
(Original Post)
- This post is a follow on from another question asked here on stack, due to the nature of the question changing, and the comments getting fairly confusing I was asked to open a new thread.
Below I'll post two snippets, one is of the original build, built with the aid of user #acontell. The other is an example of the type of result I am after, built with the aid of, user #Rajesh. Link to (Example Source).
The Base Build
// Control UI...
(function(domElements, cbState) {
// Number increment
var total = 0 + ' mm';
document.getElementById('adjvar').value = total;
function clickCallback() {
toggleElements(this.className);
}
function toggleElements(className, initialShow) {
var checkNumber = ((/ editoropt(\d*) /).exec(className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0],
isShown = initialShow === undefined ? window.getComputedStyle(division).display === 'none' : initialShow;
division.style.display = isShown ? 'block' : 'none';
checkBox.checked = isShown;
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// increment count...
var val = 30;
total += (+val * (checkBox.checked ? 1 : -1));
document.getElementById('adjvar').value = total + ' mm';
document.getElementsByClassName('adjvar').value = checkBox.checked ? val : 0 + ' mm';
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
}
domElements
.filter(function(el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function(el, index) {
el.addEventListener('click', clickCallback, false);
toggleElements(el.className, cbState[index]);
});
})([].slice.call(document.querySelectorAll('.seq-box-form-field')), [false, false]);
// Default Checked...
if (document.getElementById('checkboxopt').checked) {
// do nothing
} else {
document.getElementById('checkboxopt').click();
}
// inject style
function ctSe() {
var css = "input[type='checkbox'] { float:left; margin-right: 1em !important;}",
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
console.log(head)
console.log(style)
console.log(css)
};
ctSe();
.editoraccvar {
width: 300px;
background: #f0f;
padding: .5em;
}
.editoropt {
width: 300px;
background: #0f0;
padding: .5em;
}
.editoraccvar1 {
width: 300px;
background: #0ff;
padding: .5em;
}
.editoropt1 {
width: 300px;
background: #ff0;
padding: .5em;
}
textarea {
display: block;
width: 95%;
resize: none;
padding: .5em;
}
<!-- I'm trying to hide & show this entire division... -->
<div class="seq-box-form-field field-summernote editoraccvar ">
<label for="accvar1">Ground Floor Info</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Using only what the system has supplied. -->
<div class="seq-box-form-field editoropt ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span>
<input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<!-- Secondary Division -->
<div class="seq-box-form-field field-summernote editoraccvar1 ">
<label for="accvar1">First Floor</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Secondary Checkbox -->
<div class="seq-box-form-field editoropt1 ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">First Floor </span>
<input type="checkbox" name="checkboxopt1" id="checkboxopt1" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<input name="adjvar" id="adjvar" readonly>
The Example
(function() {
var total = 0;
function calculate(index) {
var el = document.getElementsByClassName('checkbox-input')[index];
var val = el.getAttribute("data-value");
total += (+val * (el.checked ? 1 : -1));
document.getElementById('pnvar').value = total;
document.getElementsByClassName('pnvar')[index].value = el.checked ? val : 0;
}
function registerEvents() {
var cbs = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(cbs, function(cb, i) {
cb.addEventListener("click", function() {
calculate(i);
});
});
document.getElementById('pnvar').addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
})
}
window.addEventListener('load', function() {
registerEvents();
calculate(0)
})
})()
.editoropt {
font-family: Calibri, sans-serif;
width: 160px;
background: #f8f8ff;
padding: .5em;
border: solid 1px #ddd;
}
#checkboxopt {
float: left;
margin-right: 1em;
margin-top: 4px;
}
#checkboxopt1 {
float: left;
margin-right: 1em;
margin-top: 4px;
}
.pnvar {
width: 95%;
}
input:-moz-read-only {
/* For Firefox */
background-color: transparent;
border: none;
border-width: 0px;
}
input:read-only {
background-color: transparent;
border: none;
border-width: 0px;
}
<div class="seq-box-form-field editoropt ">
<label for="opt1">
<span style="padding-right: 10px; vertical-align: 1px;">Default 80mm </span>
<input type="checkbox" class="checkbox-input" data-value="80" name="checkboxopt" id="checkboxopt" value="true" checked />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<div class="seq-box-form-field editoropt ">
<label for="opt1">
<span style="padding-right: 10px; vertical-align: 1px;">Add 30mm </span>
<input type="checkbox" class="checkbox-input" name="checkboxopt1" data-value="30" id="checkboxopt1" value="true" />
<input type="hidden" name="opt2" id="opt2" value="true" />
</label>
</div>
<div class="editoropt">
<input id="pnvar" name="pnvar" placeholder="Null" onkeydown="" value="" class="required" type="text">
<input name="adjvar" class="pnvar" id="adjvar" readonly value="0">
<input name="adjvar" class="pnvar" id="adjvar2" readonly value="0">
</div>
As I mentioned in my previous post, I'm not a JS Whizz and I'm just finding my feet, however I am abitious to learn and further my knowledge. Any assistance would be greatly appreciated.
Note : All tags, classes and names, must remain the same for consistancy with another application.
I might be mistaken but I think that this two lines of code:
// Default Checked...
if (document.getElementById('checkboxopt').checked) {
// do nothing
} else {
document.getElementById('checkboxopt').click();
}
Could be avoided if you passed [true, false] as the initial states of the checkboxes:
([].slice.call(document.querySelectorAll('.seq-box-form-field')), [true, false]);
I might be wrong, you might be doing something else or the state of the page could require that click, I don't know.
Going back to the issue, if you want to increase/decrease by 30 when the checkbox is checked/unchecked, you could do as follows:
Create a function that retrieves the value of the input an updates it with a quantity added to it. The value of the input is a string of the form 'x mm' so a bit of tinkering is necessary to get the integer part of the value.
function updateInputValue(n) {
var actual = +document.getElementById('adjvar').value.split(' mm')[0] || 0;
document.getElementById('adjvar').value = (actual + n) + ' mm';
}
Inside toggleElement call this function in order to update the input value.
var increment = isShown ? 30 : -30;
updateInputValue(initialShow === undefined ? increment : +initialShow * 30);
It gets a bit complicated because you have to control the initial state of the inputs, but it's not that hard: if it's the initial state, initialShow is different from undefined so we transform the value (it's a boolean) into a number a multiply it by 30 (when it's checked, it'd be 1 * 30, when it's unchecked it'd be 0 * 30). When it's not the initial state, we increment/decrement depending on whether it's checked or not.
And here's the fiddle (I also commented out the part that clicked the checkbox). Hope it helps.
Related
I am coding a survey page for a client and they want it so that if someone selects "3" out of a 5 button question scale that buttons 1-3 have a green backgroun...4 would have 1-4, etc.
Currently, if you click a button from the number scale only the one you click is highlighted green. What I want to have is so that it changes the background color of all buttons leading up to the one clicked (If you click 2 then it would change the 1 and 2 buttons to green).
Any help appreciated
Main code for the survey here (1 button example- the rest follow the same format):
<section class="l-reviews pt-30 pb-15">
<div class="contain">
<div class="row">
<div class="col-md-12">
<div class="reviews-wrapper">
<div class="reviews-top-header">
<p id="">Thank you for taking part. Please complete this survey to let us know how we’re
doing.</p>
<p>Please rate the following on a 1-5 scale (1 = Least, 5 = Most)</p>
</div>
<div class="reviews-body">
<form method='post' name='front_end' action="">
<div class="form-control">
<p>1. Were the payroll process and benefits options explained to you fully?</p>
<div class="input-holder">
<input type='hidden' name='title' value='' />
<input type='hidden' name='email' value='' />
<input type="radio" data='Unsatisfied' name='satisfaction' value='20' id='sat-1' /><label for="sat-1"></label>
<input type="radio" data='Not Very Satisfied' name='satisfaction' value='40' id='sat-2' /><label for="sat-2"></label>
<input type="radio" data='Neutral' name='satisfaction' value='60' id='sat-3' /><label for="sat-3"></label>
<input type="radio" data='Satisfied' name='satisfaction' value='80' id='sat-4' /><label for="sat-4"></label>
<input type="radio" data='Highly Satisfied' name='satisfaction' value='100' id='sat-5' /><label for="sat-5"></label>
<div class="error">
<p>Please select at least one option.</p>
</div>
</div>
</div>
<button type="button" class="send-btn">Submit</button>
<input type="hidden" name="action" value="review" />
</form>
<div class='success-form'>
<h3>Your review was submitted successfully</h3>
</div>
</div>
CSS for one button:
input[type=radio]:not(.regular-radio) {
display: none;
}
#wr-1+label,
#application-rating-1+label,
#goals-rating-1+label,
#refer-rating-1+label,
#sat-1+label {
background: url('/wp-content/themes/theme52950/images/reviews-faces/button-1.png');
height: 55px;
width: 109px;
display: inline-block;
padding: 0 0 0 0px;
background-repeat: no-repeat;
}
#wr-1:checked+label,
#application-rating-1:checked+label,
#goals-rating-1:checked+label,
#refer-rating-1:checked+label,
#sat-1:checked+label {
background: url('/wp-content/themes/theme52950/images/reviews-faces/1-hover.png');
height: 55px;
width: 109px;
display: inline-block;
padding: 0 0 0 0px;
background-repeat: no-repeat;
}
JavaScript:
<script>
$(document).ready(function() {
console.log(emailsArray);
$('input[type=radio]').click(function() {
avgOne = parseInt($('input[name=satisfaction]:checked').val());
avgTwo = parseInt($('input[name=working_rating]:checked').val());
avgThree = parseInt($('input[name=application_rating]:checked').val())
avgFour = parseInt($('input[name=goals_rating]:checked').val())
avgFive = parseInt($('input[name=refer_rating]:checked').val())
avgOfAll = ((avgOne + avgTwo + avgThree + avgFour + avgFive) / 5);
if (avgOfAll < 80) {
$('.addtl-comments').show();
} else {
$('.addtl-comments').hide();
}
})
if (checkOne && checkTwo && checkThree && checkFour && checkFive && addtlComments && checkEmailExist && emailNotDupe) {
$('.reviews-body form').submit();
const portalId = '3112753';
const formId = '23212b77-0a27-4833-93a9-766bdf8c3a9b';
const url = 'https://api.hsforms.com/submissions/v3/integration/submit/' + portalId + '/' + formId;
const body = {
context: {
pageUri: window.location.href,
pageName: $(document).find("title").text()
},
fields: [{
name: 'email',
value: getUrlParameter('email')
}, {
name: 'how_satisfied_are_you_with_the_overall_experience_in_working_with_',
value: document.querySelector('input[name="satisfaction"]:checked').getAttribute('data')
}, {
name: 'how_would_you_rate_working_with_your_recruiter_',
value: document.querySelector('input[name="working_rating"]:checked').getAttribute('data')
}, {
name: 'how_would_you_rate_the_application_process_',
value: document.querySelector('input[name="application_rating"]:checked').getAttribute('data')
}, {
name: 'how_satisfied_were_you_with_communication_throughout_your_interview_process_',
value: document.querySelector('input[name="goals_rating"]:checked').getAttribute('data')
}, {
name: 'how_likely_would_you_be_to_recommend_to_other_candidates_',
value: document.querySelector('input[name="refer_rating"]:checked').getAttribute('data')
}]
};
Any help appreciated.
A minimal reproducable example would have been sufficient. Just for fun: here's an idea for you:
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.dataset.scoreid) {
const score = +evt.target.dataset.scoreid;
const stars = document.querySelectorAll(`[data-scoreid]`)
.forEach((el, i) =>
el.classList[i <= score ? `add` : `remove`](`starred`));
const rateEl = evt.target.closest(`#rate`);
rateEl.classList.remove(`single`, `score`);
rateEl.classList.add(score + 1 === 1 ? `single` : `scored`);
rateEl.dataset.score = score + 1;
}
}
document.body.insertAdjacentHTML(
`beforeEnd`,
`<div id="rate" date-score="0" data-single="0">
${[...Array(5)].map((v, i) => `<span data-scoreid="${i}"></span>`)
.join(``)}
</div>`);
#rate {
font-size: 2rem;
}
#rate.scored:after {
content: 'you scored 'attr(data-score)' stars' ;
color: green;
}
#rate.single:after {
content: 'you scored 'attr(data-score)' star' ;
color: green;
}
#rate span {
cursor: pointer;
}
#rate span:before {
content: '\2606'
}
#rate span.starred:before {
content: '\2605';
color: green;
}
What I don't understand is why does my code not change the text of the label when the radio is selected?
This is what is suppose to happen:
Which when 'Fahrenheit to Celsius' is selected the first image should be true (the text of the first and second label should change)
When 'Celsius to Fahrenheit' is selected the second image should be true (the text of the first and second label should change)
What I'm guessing is my problem is with the if ($("input:to_celsius").val() == "true") statement but I don't quite know why it's wrong.
***Current error message:
{
"message": "Uncaught TypeError: Cannot set property 'onclick' of null",
"filename": "https://stacksnippets.net/js",
"lineno": 69,
"colno": 30
}
"use strict";
var $ = function(id) { return document.getElementById(id); };
var clearTextBoxes = function() {
$("#degrees_entered").value = "";
$("#degrees_computed").value = "";
};
window.onload = function() {
$("#to_celsius").onclick = toCelsius;
$("#to_fahrenheit").onclick = toFahrenheit;
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").val() == "true") {
$("#degree_labl_1").text("Enter C degrees");
$("#degree_label_2").text("Degrees Fahrenheit");
clearTextBoxes();
}
}
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").val() == "true") {
$("#degree_labl_1").text("Enter F degrees");
$("#degree_label_2").text("Degrees Celsius");
clearTextBoxes();
}
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: .5em;
}
#convert {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert Temperatures</title>
<link rel="stylesheet" href="styles.css">
<script src="convert_temp.js"></script>
<script src="jquery-3.4.1.min.js"></script>
</head>
<body>
<main>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" ><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
</body>
</html>
There are multiple issues in your code.
Looks like you are trying to use jQuery here, but in your case you are overriding the jQuery $ function with a custom function. So in effect you are not using jQuery here by calling the $ function but using pure javascript selectors
var $ = function(id) {
return document.getElementById(id);
};
With a function declaration as above, you can select elements only by Id and the Id should not be prefixed with #
$("#degree_label_1") won't work here
$("degree_label_1") will work.
So I suggest changing the $ function declaration to something like below.
var $ = function(selector) {
return document.querySelector(selector);
};
Here I changed document.getElementById -> document.querySelector so that selectors are more flexible (You can use any css selectors like "#id", ".classname" etc)
As we are not using jQuery here, the below code will not work. In jQuery, its correct but there are syntax differences in accessing the dom in plain javascript
$("#to_fahrenheit").val() == "true"
One way to implement the same is..
Assign values to the radio button inputs
<input
type="radio"
name="conversion_type"
id="to_celsius"
value="f_to_c"
checked
/>Fahrenheit to Celsius<br />
<input
type="radio"
name="conversion_type"
id="to_fahrenheit"
value="c_to_f"
/>Celsius to Fahrenheit<br />
and check the value
$("#to_fahrenheit").value == "c_to_f"
Same applies to the below line. There's a typo as well (Missed an e in degree_label_1)
$("#degree_labl_1").text("Enter F degrees")
should be changed to
$("#degree_label_1").textContent = "Enter F degrees"
Complete code would look like below.
"use strict";
var $ = function(id) {
return document.querySelector(id);
};
var clearTextBoxes = function() {
$("#degrees_entered").value = "";
$("#degrees_computed").value = "";
};
window.onload = function() {
$("#to_celsius").onclick = toCelsius;
$("#to_fahrenheit").onclick = toFahrenheit;
$("#convert").onclick = convert;
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").value == "c_to_f") {
$("#degree_label_1").textContent = "Enter C degrees";
$("#degree_label_2").textContent = "Degrees Fahrenheit";
clearTextBoxes();
}
};
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").value == "f_to_c") {
$("#degree_label_1").textContent = "Enter F degrees";
$("#degree_label_2").textContent = "Degrees Celsius";
clearTextBoxes();
}
};
var convert = function() {
var conversiontype = $(
'[name="conversion_type"]:checked'
).value;
var enteredValue = Number($("#degrees_entered").value);
if (conversiontype === "f_to_c") {
$("#degrees_computed").value = ((enteredValue - 32) * 5) / 9;
} else {
$("#degrees_computed").value = (enteredValue * 9) / 5 + 32;
}
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 0.5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: 0.5em;
}
#convert {
width: 10em;
}
<h1>Convert temperatures</h1>
<input
type="radio"
name="conversion_type"
id="to_celsius"
value="f_to_c"
checked
/>Fahrenheit to Celsius<br />
<input
type="radio"
name="conversion_type"
id="to_fahrenheit"
value="c_to_f"
/>Celsius to Fahrenheit<br /><br />
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" /><br />
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled /><br />
<label> </label>
<input type="button" id="convert" value="Convert" /><br />
If you want to use jQuery, you should remove below function declaration
var $ = function(id) {
return document.getElementById(id);
};
And modify your code as follows.
"use strict";
var clearTextBoxes = function() {
$("#degrees_entered").val("");
$("#degrees_computed").val("");
};
window.onload = function() {
$("#to_celsius").on("click", toCelsius);
$("#to_fahrenheit").on("click", toFahrenheit);
$("#convert").on("click", convert);
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").val() == "c_to_f") {
$("#degree_label_1").text("Enter C degrees");
$("#degree_label_2").text("Degrees Fahrenheit");
clearTextBoxes();
}
};
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").val() == "f_to_c") {
$("#degree_label_1").text("Enter F degrees");
$("#degree_label_2").text("Degrees Celsius");
clearTextBoxes();
}
};
var convert = function() {
var conversiontype = $(
'[name="conversion_type"]:checked'
).val();
var enteredValue = Number($("#degrees_entered").val());
if (conversiontype === "f_to_c") {
$("#degrees_computed").val(((enteredValue - 32) * 5) / 9);
} else {
$("#degrees_computed").val((enteredValue * 9) / 5 + 32);
}
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 0.5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: 0.5em;
}
#convert {
width: 10em;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" value="f_to_c" checked />Fahrenheit to Celsius<br />
<input type="radio" name="conversion_type" id="to_fahrenheit" value="c_to_f" />Celsius to Fahrenheit<br /><br />
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" /><br />
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled /><br />
<label> </label>
<input type="button" id="convert" value="Convert" /><br />
I started to learn javascript 2 weeks ago. I want to do my first program which counts all prices from checked input.
But i dont have idea how to do this.
I found something on internet and stackoverflow, but i dont know to do this for my inputs.
Could you help me?
My code
// this function counts all the values
function showPrice() {
var priceOne = document.getElementsByName('price1');
var priceTwo = document.getElementsByName('price2');
var priceThree = document.getElementsByName('price3');
}
You can do this by getting a list of elements for all the inputs, check the ones that are checked, get their values, convert them to numbers and sum them.
Beginning with a list of ids, use Array.map() to transform the list into a list of string ids (1 -> test1).
Then apply getElementById() to each id to get the HTML element.
Then from the element extract and convert the value if the input is checked, otherwise map the element to 0.
Use Array.reduce to sum the values.
Using getElementById, find your output span and set its innerHTML to the total.
function showPrice() {
const total = [1,2,3,4,5,6,7,8,9]
.map(id => `test${id}`)
.map(id => document.getElementById(id))
.map(el => el && el.checked ? Number(el.value) : 0)
.reduce((sum, value) => sum + value, 0);
document.getElementById('getPrice').innerHTML = total;
}
.priceInput {
display: block;
border: 1px solid black;
padding: 10px;
width: 300px;
text-align: center;
margin-left: auto;
margin-right: auto;
}
.priceOutput {
display: block;
border: 1px solid black;
padding: 10px;
width: 300px;
text-align: center;
margin-left: auto;
margin-right: auto;
}
<div class="priceInput">
<p>Part 1</p>
<label for="test1">test1</label>
<input type="radio" name="price1" id="test1" value="10">
<label for="test2">test2</label>
<input type="radio" name="price1" id="test2" value="25">
<label for="test3">test3</label>
<input type="radio" name="price1" id="test3" value="12">
</div>
<div class="priceInput">
<p>Part 2</p>
<label for="test4">test4</label>
<input type="radio" name="price2" id="test4" value="5">
<label for="test5">test5</label>
<input type="radio" name="price2" id="test5" value="7">
<label for="test6">test6</label>
<input type="radio" name="price2" id="test6" value="2">
</div>
<div class="priceInput">
<p>Part 3</p>
<label for="test7">test7</label>
<input type="radio" name="price3" id="test7" value="250">
<label for="test8">test8</label>
<input type="radio" name="price3" id="test8" value="720">
<label for="test9">test9</label>
<input type="radio" name="price3" id="test9" value="410">
</div>
<br>
<div class="priceOutput">
<button onclick="showPrice()">Show Price</button>
<p>Your Price is : <span id="getPrice">0<!--Here i want to get price1(value) + price2(value) + price3(value)--></span> $</p>
</div>
By looking at your code, it seems that you want to get the option the user selected out of the radio buttons and not all radio buttons (referring to the getElementsByName). To do so, you can go over the nodeList returned and see if any of the elements have the checked property.
for(let i = 0; i < priceOne.length; i++){
if(priceOne[i].checked) {
//Get value of the price selected with .value
let priceOneValue = priceOne[i].value;
}
}
After doing this for all your input types, you can sum them up.
JO_VA here is my own code. Can you check it? It's easier for my understanding.
I found just 1 problem and it is : when i remove from HTML input tag "checked" and i klikn only for 1 or 2 radio options, it show NaN in paragraph for price.
BTW sorry for my english (i ussually dont use english language)
function showPrice(){
var pricePlace = document.getElementById("getPrice");
getVal1();
getVal2();
getVal3();
var InputNumber = Number(inputVal1) + Number(inputVal2) + Number(inputVal3);
pricePlace.innerHTML = InputNumber;
}
var inputVal1;
function getVal1(){
var a = document.getElementById("test1");
var b = document.getElementById("test2");
var c = document.getElementById("test3");
if (c.checked) {
inputVal1 = c.value;
}
if (b.checked) {
inputVal1 = b.value;
}
if (a.checked) {
inputVal1 = a.value;
}
}
var inputVal2;
function getVal2(){
var a = document.getElementById("test4");
var b = document.getElementById("test5");
var c = document.getElementById("test6");
if (c.checked) {
inputVal2 = c.value;
}
if (b.checked) {
inputVal2 = b.value;
}
if (a.checked) {
inputVal2 = a.value;
}
}
var inputVal3;
function getVal3(){
var a = document.getElementById("test7");
var b = document.getElementById("test8");
var c = document.getElementById("test9");
if (c.checked) {
inputVal3 = c.value;
}
if (b.checked) {
inputVal3 = b.value;
}
if (a.checked) {
inputVal3 = a.value;
}
}
Or you can check it in https://codepen.io/soorta/pen/gqEGyQ
I am trying to get all the checkbox checked values on the input field provided. I am using javascript to get the values but it only shows one checked value. When I check another checkbox it displays the second one only.
Here is what i did so far:
<html>
<head>
<script type="text/javascript">
function checkbox(val){
document.getElementById("show").value = val;
}
</script>
</head>
<body>
<form>
<input type="checkbox" id="bk" name="vehicle" onClick="checkbox(this.value);" value="Bike">I have a bike<br></br>
<input type="checkbox" id="cr" name="vehicle" onClick="checkbox(this.value);" value="Car">I have a car<br></br>
<input type="text" id="show" name="vehicle"><br>
<input type="submit" value="Showe">
</form>
</body>
</html>
As I said, this one only shows a single checked value, but I want to show all the checked values on the input field specified!
Thanks!
Your code is only sending the currently clicked item to the method. You need to look at all the checkboxes in that method and find the checked ones, put them in an array, then insert the array value into your input. Also worth noting, when you do it this way and build out the array on each click, it also makes it appear as though items are being removed from the input when you uncheck them.
function checkbox(){
var checkboxes = document.getElementsByName('vehicle');
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i].value);
}
}
document.getElementById("show").value = checkboxesChecked;
}
<form>
<input type="checkbox" id="bk" name="vehicle" onClick="checkbox();" value="Bike">I have a bike<br></br>
<input type="checkbox" id="cr" name="vehicle" onClick="checkbox();" value="Car">I have a car<br></br>
<input type="text" id="show" name="vehicle"><br>
<input type="submit" value="Showe">
</form>
var txt = document.getElementById( 'droptxt' ),
content = document.getElementById( 'content' ),
list = document.querySelectorAll( '.content input[type="checkbox"]' ),
quantity = document.querySelectorAll( '.quantity' );
txt.addEventListener( 'click', function() {
content.classList.toggle( 'show' )
} )
window.onclick = function( e ) {
if ( !e.target.matches( '.list' ) ) {
if ( content.classList.contains( 'show' ) ) content.classList.remove( 'show' )
}
}
list.forEach( function( item, index ) {
item.addEventListener( 'click', function() {
calc()
} )
} )
function calc() {
for ( var i = 0, arr = []; i < list.length; i++ ) {
let spanArray = [];
document.querySelectorAll('span').forEach(element => {
spanArray.push(element.innerHTML);
});
if ( list[ i ].checked ) arr.push( list[ i ].value + " "+ spanArray)
}
txt.value = arr.join(', ')
}
h1 {
color: #0000ff;
}
#droptxt {
padding: 8px;
width: 300px;
cursor: pointer;
box-sizing: border-box
}
.dropdown {
position: relative;
display: inline-block
}
.content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 200px;
overflow: auto;
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, .2);
z-index: 1
}
.content div {
padding: 10px 15px
}
.content div:hover {
background-color: #ddd
}
.show {
display: block
}
<h1>KIAAT</h1>
<b>Adding/Removing Checkbox Values into TextArea</b>
<br><br>
<input type="text" id="droptxt" class="list" placeholder="Select the values" readonly>
<div id="content" class="content">
<div id="market" class="list">
<label><input type="checkbox" id="market" class="list" value="Bike" /> I have a bike</label>
</div>
<div class="list">
<label><input type="checkbox" id="banana" class="list" value="Car" /> I have a car</label>
</div>
</div>
I posted a similar question yesterday, but this is new problem.
I have dynamically created Check Boxes on a page. On is the Parent Check Box and the rest are the child check boxes. Each Child Check Box is wrapped in a <div>. I have a drop down list. When I select an item from the list, the Check Boxes gets checked or unchecked. When the check box state changes, the <div> in witch it is wrapped background colour changes or when I check or uncheck it.
My problem. When I check/uncheck the parent check box it also checks/unchecks the child ones, but the background colour of the child check boxes' <div> does not change.
I need it to still work as it is currently working but also to have the new feature as required.
My Code:
1. CSS:
<style>
div.sch_cal_row {
margin-top: 0px;
margin-left: 0px;
width: 300px;
border-radius: 3px;
border-color: white;
height: 20px;
}
div.highlight {
width: 300px;
height: 20px;
background-color: #78EF5A;
/*background-color: #E0FBD9;*/
/*background-color: green;*/
}
div.high1 {
width: 300px;
height: 20px;
background-color: #F24F40;
/*background-color: #FFA07A;*/
/*background-color: red;*/
}
div.available {
width: 100px;
height: 46px;
background-color: #A8A69C;
}
</style>
2. JS:
<script type="text/javascript">
$(".childChk").each(function(){
check($(this));
});
$(".childChk").click(function () {
check($(this));
});
function check(chkElem) {
if (chkElem.is(':checked')) {
chkElem.parent().removeClass();
chkElem.parent().addClass("highlight");
} else {
chkElem.parent().removeClass("highlight");
chkElem.parent().addClass("high1");
}
}
</script>
3. HTML/Razor:
<div id="Priv">
#for (var i = 0; i < Model.Categories.Count; i++)
{
<div>
#Html.CheckBoxFor(m => Model.Categories[i].AllChecked, new { id = Model.Categories[i].CategoryID, #class = "parentChk" })
#Html.HiddenFor(m => Model.Categories[i].CategoryName)
<strong>#Model.Categories[i].CategoryName</strong>
<br />
#*#Html.JTDisplayTextFor(m => Model.Categories[i].CategoryName, "")*#
#for (var p = 0; p < Model.Categories[i].Privileges.Count; p++)
{
<div class="sch_cal_row">
#Html.HiddenFor(m => Model.Categories[i].Privileges[p].PrivilegeID)
#Html.HiddenFor(m => Model.Categories[i].Privileges[p].PrivilegeName)
#Html.CheckBoxFor(m => Model.Categories[i].Privileges[p].Checked, new { #class = "childChk" })
#Html.JTDisplayTextFor(m => Model.Categories[i].Privileges[p].PrivilegeName, "")
</div>
}
<br />
</div>
}
</div>
UPDATE as per comment:
<input class="parentChk" data-val="true" data-val-required="The AllChecked field is required." id="4" name="Categories[0].AllChecked" type="checkbox" value="true">
<input name="Categories[0].AllChecked" type="hidden" value="false">
<input id="Categories_0__CategoryName" name="Categories[0].CategoryName" type="hidden" value="Account">
<strong>Account</strong>
<br>
<div class="sch_cal_row high1">
<input data-val="true" data-val-number="The field PrivilegeID must be a number." data-val-required="The PrivilegeID field is required." id="Categories_0__Privileges_0__PrivilegeID" name="Categories[0].Privileges[0].PrivilegeID" type="hidden" value="8">
<input id="Categories_0__Privileges_0__PrivilegeName" name="Categories[0].Privileges[0].PrivilegeName" type="hidden" value="AccountAddEdit">
<input class="childChk" data-val="true" data-val-required="The Checked field is required." id="Categories_0__Privileges_0__Checked" name="Categories[0].Privileges[0].Checked" type="checkbox" value="true"><input name="Categories[0].Privileges[0].Checked" type="hidden" value="false">
AccountAddEdit<br>
</div>
This is only the parent and one child.
You right your javascript code in document.ready
$(document).ready(function(e) {
$(".childChk").each(function(){
check($(this));
});
$(".childChk").click(function () {
check($(this));
});
});
function check(chkElem) {
if (chkElem.is(':checked')) {
chkElem.parent().removeClass();
chkElem.parent().addClass("highlight");
} else {
chkElem.parent().removeClass("highlight");
chkElem.parent().addClass("high1");
}
}
Try this code...
$('.childChk').on("click", function(){
var thisParent = $(this).parent();
if(thisParent.hasClass("highlight")) {
thisParent.removeClass("highlight")
} else {
thisParent.addClass("highlight")
}
});