show checked checkbox values on textarea javascript - 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>

Related

How to change the text of a label when a radio button is selected

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 />

How to write code for counts prices from checked inputs

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

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.

How do I check to make sure all my input:radio elements have a value?

I'm working on a form, and I've got a code that works for validating radio fields. However I plan on having many, MANY radio fields and I feel that my current method, which names each radio field individually, to be a bit tedious. I feel there must be a way I can simply select all of them to make sure they've all been checked before processing the form.
Here is my jsFiddle
Current jQuery
$("form").on("keyup change", function(){
food = $(":checked[name=food]");
color = $(":checked[name=color]");
if (food.val() == "" || food.val() == undefined ||
color.val() == "" || color.val() == undefined){
//Do stuff
} else {
//Do other stuff
}
});
jQuery I'm trying
$("form").on("keyup change", function(){
radio_req = $(".required:checked[type=radio]");
if ( radio_req == "" || radio_req == undefined ) {
//Do stuff
} else {
//Do other stuff
}
});
With the 2nd one, I'm trying to see if I can just add a class of required to all my radio fields, and then just see if any .required radio buttons are left unselected/undefined. I feel there has to be a way for this to work. Am I on the right track? I feel like I'm just not selecting this right.
I have updated your fiddle, check it !
I hope it will solve your problem.
You can test the snippet under.
This is the part i modified :
var checker = function(){
var checked = $.unique($(".required:checked[type=radio]").map(function(){
return this.name;
}));
var not_checked = $.unique($(".required:not(:checked)[type=radio]").map(function(){
return this.name;
}));
if (checked.length !== not_checked.length){
$("#submit").prop("disabled", true).removeClass("valid").addClass("invalid");
$(".submit").text("* All fields must be completed and contain valid entries before submitting.");
} else {
$("#submit").prop("disabled", false).removeClass("invalid").addClass("valid");
$(".submit").text("");
}
};
$("form").on("keyup change", checker);
checker();
$(document).ready(function(){
// for each Question we have 3 choices:
// so when we answer we have 1 checked and 2 unchecked
// we loop over question
// we fill 2 arrays(checked, unchecked)
// with names of radio
// for each question we will have something like that
// Question 1 : food
// checked = ['food']; notchecked = ['food','food']
// we make them unique ! it becomes
// checked = ['food']; notchecked = ['food'];
// we know now that the First question have been answered
// we loop over all question :
// checked = ['food'] , notchecked = ['food' , 'color' , 'town' , 'country' , 'car']
// we wait for checking !
// let answer Qestion 2
// checked = ['food' , 'color] , notchecked = ['food' , 'color' , 'town' , 'country' , 'car']
// etc etc . . .
// when checked.length === notchecked.length => we have an answer for all question
var checker = function(){
var checked = $.unique(
$(".required:checked[type=radio]").map(function(){
return this.name;
})
);
var not_checked = $.unique(
$(".required:not(:checked)[type=radio]").map(function(){
return this.name;
})
);
if (checked.length !== not_checked.length){
$("#submit").prop("disabled", true).removeClass("valid").addClass("invalid");
$(".submit").text("* All fields must be completed and contain valid entries before submitting.");
} else {
$("#submit").prop("disabled", false).removeClass("invalid").addClass("valid");
$(".submit").text("");
}
};
$("form").on("keyup change", checker);
checker();
});
input {
margin: 7px;
}
.valid {
background-color: green;
border: 3px solid darkgreen;
color: white;
}
.invalid {
background-color: grey;
border: 3px solid darkgrey;
color: black;
}
.error {
color: red;
}
#submit {
display: block;
border-radius: 10px 10px 10px 10px;
width: 130px;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<br>Which of the following do you like the most?
<br>
<input type="radio" class="required" name="food" value="pizza">Pizza
<input type="radio" class="required" name="food" value="burgers">Burgers
<input type="radio" class="required" name="food" value="Salads">Salads
<br>
<br>Which of the following colors do you like the most?
<br>
<input type="radio" class="required" name="color" value="red">Red
<input type="radio" class="required" name="color" value="blue">Blue
<input type="radio" class="required" name="color" value="yellow">Yellow
<br>
<br>Which of the following town do you like the most?
<br>
<input type="radio" class="required" name="town" value="red">New York
<input type="radio" class="required" name="town" value="blue">Miami
<input type="radio" class="required" name="town" value="yellow">Las Vegas
<br>
<br>Which of the following country do you like the most?
<br>
<input type="radio" class="required" name="country" value="red">USA
<input type="radio" class="required" name="country" value="blue">Canada
<input type="radio" class="required" name="country" value="yellow">Chili
<br>
<br>Which of the following car do you like the most?
<br>
<input type="radio" class="required" name="car" value="red">Ferrari
<input type="radio" class="required" name="car" value="blue">Dodge
<input type="radio" class="required" name="car" value="yellow">Chevrolet
<br><br>
<input type="submit" id="submit" class="invalid">
<span class="submit error"></span>
</form>
You can iterate through all the radio buttons that have a name attribute :radio[name] in combination with an array, say examined, that helps you skip buttons that have already been checked. This should be work irrespective of how many sets of radio buttons there are in you form.
$('form').on('input change', function(e) {
e.preventDefault();
var all_selected = true;
var examined = [];
$(':radio[name]').each(function() {
if( examined.indexOf( this.name ) === -1 ) {
examined.push( this.name );
if( !$(':radio:checked[name=' + this.name + ']').length ) {
all_selected = false;
return false;
}
}
});
if( all_selected ) {
//DO STUFF
} else {
//DO OTHER STUFF
}
});
$(function() {
$('form').on('input change', function(e) {
e.preventDefault();
var all_selected = true;
var examined = [];
$(':radio[name]').each(function() {
if( examined.indexOf( this.name ) === -1 ) {
examined.push( this.name );
if( !$(':radio:checked[name=' + this.name + ']').length ) {
all_selected = false;
return false;
}
}
});
if( all_selected ) {
//DO STUFF
console.log( 'All parts completed' );
} else {
//DO OTHER STUFF
console.log( 'Form not complete' );
}
});
});
input {
margin: 7px;
}
.valid {
background-color: green;
border: 3px solid darkgreen;
color: white;
}
.invalid {
background-color: grey;
border: 3px solid darkgrey;
color: black;
}
.error {
color: red;
}
#submit {
display: block;
border-radius: 10px 10px 10px 10px;
width: 130px;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Which of the following do you like the most?<br>
<input type="radio" class="required" name="food" value="pizza">Pizza
<input type="radio" class="required" name="food" value="burgers">Burgers
<input type="radio" class="required" name="food" value="Salads">Salads <br><br>
Which of the following colors do you like the most?<br>
<input type="radio" class="required" name="color" value="red">Red
<input type="radio" class="required" name="color" value="blue">Blue
<input type="radio" class="required" name="color" value="yellow">Yellow
<input type="submit" id="submit" class="invalid">
<span class="submit error"></span>
</form>

Changing <div> Background on Check Box check

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")
}
});

Categories

Resources