How to write code for counts prices from checked inputs - javascript

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

Related

How to get score from correct answer through form input

I'm creating a quiz that contains 10 questions: 5 multiple choice through radio input and 5 written answers through text input. See code for both inputs below. But I would also like to add a score system to these questions. I found a nice script here on stack overflow that can keep the score while user enters form input. I will add it below.
The script I use to check answers from radio input:
$(document).ready(function(){
$('input[name=radio1]').change(function(){
$('.alert').remove();
if($('input[name=radio1]:checked').val() === "1") {
$(this).parent().append('<span class="correct">✓ Correct!</span>');
} else {
$(this).parent().append('<span class="incorrect">✗ Correct answer = B</span>');
}
});
});
The correct anser given is based on value="1". The other answers have value="0".
The script I use to check answers from text input:
$('submit').on('click', function() {
markAnswers(1)
});
var answers = {
q1: ["Auto's"]
};
function markAnswers(id) {
$(`#q${id}`).each(function () {
let userAnswer = this.value.replace(/[^\w\'\,\-\?\!\"\:\—\;]/g,'');
if ($.inArray(userAnswer, answers[this.id]) === -1) {
$(this).parent().append(`<br><span class='incorrect'>✗ Correct answer = ${answers[this.id]}</span>`);
} else {
$(this).parent().append("<br><span class='correct'>✓ Correct!</span>");
}
});
}
The correct value from text input is determined by this script above.
Now, the script I found that keeps the score, collects score through data-score=. But I was thinking to just use value instead. See original script below:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
The script can be found here: https://stackoverflow.com/a/58297288/4546157
It is really nice. It keeps the score but it also shows you if you have completed the form or not.
I would like each correct answer to have a value of 1 so at the end of the quiz the user can have a maximum score of 10/10. But, a big but, I don't know how to implement it. Hoping to see suggestions or solutions from you guys. Thank you!
You would do it something like this. Though it's bad practice to use globally available variables, but for the sake of simplicity i put them there. Better to wrap everything in a div and store score/progress as data attributes.
Pen: https://codepen.io/lenadax/pen/QWQqMxP?editors=1111
// global vars, put them somewhere else
var progress = 0;
var score = 0;
$('form.question').each(function(i, el) {
// I'm lazy so form id is the same as input name for each question
let inputs = $(`input[name=${$(this).attr('id')}]`);
inputs.on('change', function() {
// increase progress by 1 if button has been selected.
progress++;
if ($(this).val() === "1") {
// increase score if correct choice selected
score++;
$('<span class="result correct">').text('✓ Correct!').appendTo(el);
} else {
$('<span class="result incorrect">').text('X Incorrect!').appendTo(el);
}
// get number of questions
let question_count = $('form.question').length;
// disable after choosing for less hassle
inputs.prop('disabled', true);
// calculate the progress in percent
let progress_num = progress / question_count * 100;
$('.perc').text(progress_num);
$('#score').text(`${score} / ${question_count}`);
});
})
input {
display: inline-block;
}
label {
display: inline-block;
}
button {
display: block;
}
form {
width: 200px;
border: 1px solid gray;
margin: 10px;
padding:10px 5px;
}
.result {
display: block;
}
.result.incorrect {
color: red;
}
.result.correct {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form class="question" id="question1">
<span>Question 1</span>
</p>
<input name="question1" id="answer1" type="radio" value="0"/>
<label for="answer1">Wrong answer</label>
</p>
<input name="question1" id="answer2" type="radio" value="1"/>
<label for="answer2">Right answer</label>
</form>
<form class="question" id="question2">
<span>Question 2</span>
</p>
<input name="question2" id="answer1" type="radio" value="0"/>
<label for="answer1">Wrong answer</label>
</p>
<input name="question2" id="answer2" type="radio" value="0"/>
<label for="answer2">Wrong answer</label>
</p>
<input name="question2" id="answer3" type="radio" value="1"/>
<label for="answer3">Right answer</label>
</form>
<h5>Done <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>

How do I dynamically get the value of an element from an array of elements?

I have a form with 3 checkboxes. I'm trying to the value of whichever checkbox is clicked on. I'm able to get the value of a hardcoded checkbox index (checkbox[0] for example), but I can't get the value of checkbox[i] with vanilla JS.
document.addEventListener("DOMContentLoaded", function() {
var checkboxes = document.getElementsByClassName('checkbox');
var listType = document.getElementById('ListType');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function() {
var inputByIndex = checkboxes[0].value; //I can get the value of the first element, but I can't get the value of whichever checkbox is checked. checkbox[i] doesn't work.
listType.classList.add(inputByIndex);
var spanType = document.getElementById("type");
spanType.innerText = inputByIndex;
});
}
});
input {
margin: 20px;
}
#ListType.basiclist {
color: red;
}
#ListType.accordionlist {
color: blue;
}
#ListType.internalonly {
color: pink;
}
<form id="ListTypes">
<label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
<label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
<label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>
<div id="ListType">
List Type: <span id="type"></span>
</div>
Fiddle
You can use event.currentTarget to access the element on which event has occurred.
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM.
document.addEventListener("DOMContentLoaded", function() {
var checkboxes = document.getElementsByClassName('checkbox');
var listType = document.getElementById('ListType');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function(event) {
var inputByIndex = event.currentTarget.value;
listType.classList.add(inputByIndex);
var spanType = document.getElementById("type");
spanType.innerText = inputByIndex;
});
}
});
input {
margin: 20px;
}
#ListType.basiclist {
color: red;
}
#ListType.accordionlist {
color: blue;
}
#ListType.internalonly {
color: pink;
}
<form id="ListTypes">
<label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
<label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
<label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>
<div id="ListType">
List Type: <span id="type"></span>
</div>
In the for loop, use let instead of var to make it work:
document.addEventListener("DOMContentLoaded", function() {
var checkboxes = document.getElementsByClassName('checkbox');
var listType = document.getElementById('ListType');
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function() {
var inputByIndex = checkboxes[i].value; //I can get the value of the first element, but I can't get the value of whichever checkbox is checked. checkbox[i] doesn't work.
listType.classList.add(inputByIndex);
var spanType = document.getElementById("type");
spanType.innerText = inputByIndex;
});
}
});
input {
margin: 20px;
}
#ListType.basiclist {
color: red;
}
#ListType.accordionlist {
color: blue;
}
#ListType.internalonly {
color: pink;
}
<form id="ListTypes">
<label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
<label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
<label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>
<div id="ListType">
List Type: <span id="type"></span>
</div>
the checkboxes list doesn't exist within the closure of the onclick funcion. Instead use this.value.
JS fiddle
Delegate
You need to think of the CSS for more than one listType color or use a set of radio buttons
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('ListTypes').addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.type && tgt.type === 'checkbox') {
const values = [...tgt.form.querySelectorAll("[type=checkbox]:checked")].map(chk => chk.value);
document.getElementById("type").textContent = values.join(", ")
document.getElementById("ListType").classList.add(...values);
}
});
});
input {
margin: 20px;
}
#ListType.basiclist {
color: red;
}
#ListType.accordionlist {
color: blue;
}
#ListType.internalonly {
color: pink;
}
<form id="ListTypes">
<label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
<label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
<label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>
<div id="ListType">
List Type: <span id="type"></span>
</div>
You just need to select them all using the method you would like (I used querySelectorAll & ) and do an iteration over them (I used forEach()).
This is the most simple function you can ever find.
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(singleCheckbox => {
singleCheckbox.addEventListener('click', () => alert(singleCheckbox.id))
});
<label for="first">First<input type="checkbox" id="first"/></label>
<label for="second">Second<input type="checkbox" id="second"/></label>
<label for="third">Third<input type="checkbox" id="third"/></label>
Just to make clear what was actually the problem with your code...
At the time you click handler will be fired the for loop will end its work and thus, the value of i will become exactly checkboxes.length, and of course, there is no checkbox with such an index, because the last of them has index (checkboxes.length - 1). So the reason is that the code inside of the handler is executed after for loop ends its work.
The solutions were already provided by other users.

I want to check if the checkbox is checked, but everytime i try it always goes with the else option for everything

Im trying to make a bookshop website where the customer checks the books and writes the number of copies. But the code cannot tell if the checkbox is checked and goes with the "else" option always. What needs to change?
checkb1-5 are the checkboxes element
numbcop1-5 is the number of copies entered by the user
function Checker() {
var checkb1 = document.getElementById("adult");
if (checkb1.checked){
var numbcop1 = document.getElementById(numb1);
} else{
var numbcop1 = 0;
}
var checkb2 = document.getElementById("ado");
if (checkb2.checked){
var numbcop2 = document.getElementById(numb2);
} else{
var numbcop2 = 0;
}
var checkb3 = document.getElementById("child");
if (checkb3.checked){
var numbcop3 = document.getElementById(numb3);
} else {
var numbcop3 = 0;
}
var checkb4 = document.getElementById("school");
if (checkb4.checked){
var numbcop4 = document.getElementById(numb4);
} else {
var numbcop4 = 0;
}
var checkb5 = document.getElementById("transl");
if (checkb5.checked){
var numbcop5 = document.getElementById(numb5);
} else{
var numbcop5 = 0;
}
}
Looks like there are a few things to fix before to make your function works:
When you are doing var numbcop1 = document.getElementById(numb1); you need to make sure the parameter you are adding to getElementById is correct. E.g document.getElementById('numb1') or make sure that numb1 contains an string indicating the id for the function to look at e.g var numb1 = 'adult_amount'; and then use that variable as your code does document.getElementById(numb1)
Once you get the element that is expected to have the value, if it is an input you can do var numbcop1 = document.getElementById('numb1').value; to get the number typed by the user.
Let's refactor the Adult field to have a clear example on how it works:
<input type="checkbox" data-copies="adult_copies" id="adult">
<label>adult</label>
<input type="number" id="adult_copies">
And add this to your JS and check how the values comes using a single function that can be reused for the other books:
function getChecked(event) {
let numbcop;
let copies_id = event.target.getAttribute('data-copies');
if (event.target.checked){
numbcop = document.getElementById(copies_id).value;
} else{
numbcop = 0;
}
console.log(numbcop);
}
let adult = document.getElementById("adult");
adult.addEventListener('click', getChecked);
LMK if this works for your implementation.
actually it is going with the if option not else but it is returning zero.
You must point to the value of the numb1 not just the element.
for example:
var numbcop1 = document.getElementById(numb1).value;
at least this must be coded like this (?):
var
t_elem = ['adult', 'ado', 'child','school', 'transl'],
numbcop1 = 0,
numbcop2 = 0,
numbcop3 = 0,
numbcop4 = 0,
numbcop5 = 0
;
function Checker() {
t_elem.forEach((elm,idx)=>{
window['numbcop'+(idx+1)] = (document.getElementById(elm).checked) ? document.getElementById('numb'+(idx+1)).value : 0;
})
}
Get_Books.onclick = function() {
Checker();
console.log(numbcop1, numbcop2, numbcop3, numbcop4, numbcop5);
}
label { float:left; clear: both; display:block; width:80px; margin:10px 5px; text-align: right }
input, button { float:left; display:block; margin:10px 5px }
button { clear: both }
<label for="adult">adult: </label>
<input id="adult" type="checkbox" />
<input id="numb1" type="number" value="1" />
<label for="ado">ado: </label>
<input id="ado" type="checkbox" />
<input id="numb2" type="number" value="2" />
<label for="adult">child: </label>
<input id="child" type="checkbox" />
<input id="numb3" type="number" value="3" />
<label for="school">school: </label>
<input id="school" type="checkbox" />
<input id="numb4" type="number" value="4" />
<label for="transl">transl: </label>
<input id="transl" type="checkbox" />
<input id="numb5" type="number" value="5" />
<button id="Get_Books">Books</button>

Using Checkboxes to contol an Input.value (With an annoying twist.)

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.

show checked checkbox values on textarea javascript

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>

Categories

Resources