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")
}
});
Related
I have select all check box with some option when i click select all i select all the option and when i remove the select all i remove it from all option and the code below work for that.
What i try to do is when i unselect one of the option the select all box should be unselected and if i select all the option without selecting the select all option the check all box should be selected.
How can i do that?
let checkboxes = document.querySelectorAll("input[type = 'checkbox']");
function checkAll(myCheckBox) {
if (myCheckBox.checked == true) {
checkboxes.forEach(function(checkbox) {
checkbox.checked = true;
});
} else {
checkboxes.forEach(function(checkbox) {
checkbox.checked = false;
});
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 100vh;
display: grid;
place-content: center;
}
input[type="checkbox"] {
margin-bottom: 10px;
cursor: pointer;
}
input[type="checkbox"]:not(:first-child) {
margin-left: 20px;
}
<div class="container">
<input type="checkbox" id="check-all" onchange="checkAll(this)">
<label for="check-all">Select All</label>
<br/>
<input type="checkbox" id="option-a">
<label for="option-a">Option A</label>
<br/>
<input type="checkbox" id="option-b">
<label for="option-b">Option B</label>
<br/>
<input type="checkbox" id="option-c">
<label for="option-c">Option C</label>
<br/>
</div>
You can add a change event listener to all of those checkboxes (except for the automatic select all checkbox).
So in this demo I used a disciminant being the class auto that only the "select all" checkbox has.
Then I select all elements being input but not having the class auto.
And for each of those I add an event listener for the change event that will uncheck the "select all" checkbox if any of those was unchecked and that will check the "select all" checkbox if otherwise all of them are checked.
let checkboxes = document.querySelectorAll("input[type='checkbox']");
let cbActual = document.querySelectorAll('input[type=checkbox]:not([class=auto])');
cbActual.forEach(
cb => {
cb.addEventListener('change', (event)=>{
if(!event.target.checked)
document.getElementById('check-all')
.checked = false;
else{
if( [...cbActual].every(cb => cb.checked === true) )
document.getElementById('check-all')
.checked = true;
}
});
}
);
function checkAll(myCheckBox) {
if (myCheckBox.checked == true) {
checkboxes.forEach(function(checkbox) {
checkbox.checked = true;
});
} else {
checkboxes.forEach(function(checkbox) {
checkbox.checked = false;
});
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 100vh;
display: grid;
place-content: center;
}
input[type="checkbox"] {
margin-bottom: 10px;
cursor: pointer;
}
input[type="checkbox"]:not(:first-child) {
margin-left: 20px;
}
<div class="container">
<input type="checkbox" id="check-all" onchange="checkAll(this)" class="auto">
<label for="check-all">Select All</label>
<br/>
<input type="checkbox" id="option-a">
<label for="option-a">Option A</label>
<br/>
<input type="checkbox" id="option-b">
<label for="option-b">Option B</label>
<br/>
<input type="checkbox" id="option-c">
<label for="option-c">Option C</label>
<br/>
</div>
When checkall is clicked either all or none are selected. When one of the options are checked/unchecked the status of checkall is decided based on the filter function.
I changed the markup of the form a bit. You can "group" check boxes on their name. And try avoiding IDs in a form -- in general it is better to use the name attribute.
document.addEventListener('DOMContentLoaded', e => {
document.forms.form01.addEventListener('change', result_change);
});
function result_change(e) {
let form = e.target.form;
/* e.target.form.option could either be a NodeList or just one Element.
A iterable is needed. */
let options = (form.option.length) ? form.option : [form.option];
switch (e.target.name) {
case 'checkall':
let checked = e.target.checked;
[...options].forEach(option => option.checked = checked);
break;
case 'option':
let allchecked = ([...options].filter(option => !option.checked).length == 0) ? ? true;
form.checkall.checked = allchecked ? true : false;
break;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 100vh;
display: grid;
place-content: center;
}
input[type="checkbox"] {
margin-bottom: 10px;
cursor: pointer;
}
input[type="checkbox"]:not(:first-child) {
margin-left: 20px;
}
<form name="form01">
<input type="checkbox" name="checkall">
<label for="check-all">Select All</label>
<br/>
<input type="checkbox" name="option" value="a">
<label for="option-a">Option A</label>
<br/>
<input type="checkbox" name="option" value="b">
<label for="option-b">Option B</label>
<br/>
<input type="checkbox" name="option" value="c">
<label for="option-c">Option C</label>
<br/>
</form>
Prefer to use event propagation to handle the change events of all checkboxes in one listener.
To make use of event propagation, you have to be able to distinguish them from the "Select all" checkbox. To distinuish them, you can:
Use a class (on either the "Select all" or all other checkboxes).
Group the checkboxes (except the "Select all" checkbox) in an element.
Check if the changing checkbox is the first (i.e. the "Select all") checkbox.
...
I chose to use a grouping element so that the "Select all" checkbox is not included:
const cbAll = document.getElementById("cb-all");
const cbGroup = document.getElementById("cb-group");
// NodeList has .forEach() but not .every(). Transform to an array, which has both.
const checkboxes = Array.from(cbGroup.querySelectorAll("input[type=checkbox]"));
cbAll.addEventListener("change", () => {
// If cbAll.checked changes, cbAll.checked should override all other checkboxes' checked.
checkboxes.forEach(cb => cb.checked = cbAll.checked);
});
// This listener will be called if *any* checkbox (in cbGroup) changes.
// Update cbAll.checked to true if all checkboxes are checked; otherwise false.
cbGroup.addEventListener("change", () => {
const areAllChecked = checkboxes.every(cb => cb.checked);
cbAll.checked = areAllChecked;
});
label {display: block}
#cb-group {margin-inline-start: 1.2rem}
<label for="cb-all"><input id="cb-all" type="checkbox"> Select all</label>
<div id="cb-group">
<label for="cb-1"><input id="cb-1" type="checkbox"> First option</label>
<label for="cb-2"><input id="cb-2" type="checkbox"> Second option</label>
<label for="cb-3"><input id="cb-3" type="checkbox"> Third option</label>
</div>
Alternatively you can add listeners to all checkboxes individually.
Checkboxes can also be in a "third" state: Indeterminate. Note: This is not a true state, as checkboxes can only be either checked or unchecked. An indeterminate checkbox hides its checkedness under the pretence of being indeterminate.
This is most commonly used for checkboxes like this "Select all" checkbox; where a checkbox describes the state of a group of checkboxes.
The above example can be modified to make use of it:
const cbAll = document.getElementById("cb-all");
const cbGroup = document.getElementById("cb-group");
const checkboxes = Array.from(cbGroup.querySelectorAll("input[type=checkbox]"));
cbAll.addEventListener("change", () => {
checkboxes.forEach(cb => cb.checked = cbAll.checked);
});
cbGroup.addEventListener("change", () => {
const amountChecked = checkboxes.reduce((amount, cb) => {
// Number(bool) returns 1 if bool === true; otherwise 0.
return amount + Number(cb.checked);
}, 0);
const areAllChecked = amountChecked === checkboxes.length;
const areSomeChecked = amountChecked > 0;
cbAll.checked = areAllChecked;
cbAll.indeterminate = areSomeChecked && !areAllChecked;
});
label {display: block}
#cb-group {margin-inline-start: 1.2rem}
<label for="cb-all"><input id="cb-all" type="checkbox"> Select all</label>
<div id="cb-group">
<label for="cb-1"><input id="cb-1" type="checkbox"> First option</label>
<label for="cb-2"><input id="cb-2" type="checkbox"> Second option</label>
<label for="cb-3"><input id="cb-3" type="checkbox"> Third option</label>
</div>
I want to change width of a textfield when user enters more than 17 characters in that textfield using Javascript (if possible) otherwise by any other means.
I wrote a code to do the same, but it only changes width when user click outside the textfield after entering more than 17 characters. I want it to change width automatically when user enters more than 17 characters :
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onchange="widen()" value="" required>
</form>
onchange gets activated when the input looses focus, that's why it works when you click outside. On the other hand oninput will be triggered immediately when the value changes:
const nametf = document.getElementById('nametf');
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<html>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" oninput="widen()" value="" required>
</form>
</html>
You need to pass a self-reference to the function using this. I would also change on-change to on-key-up, because on-change waits for you to move focus away from the field.
onkeyup="widen(this)"
Then you need to parameterize the function with your variable "nametf"
function widen(nametf) {
// ...
}
Example
function widen(nametf) {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onkeyup="widen(this)" value="" required>
</form>
A better approach would be to use em units to expand the text are based on the current value.
initExpandingFields();
function initExpandingFields() {
Array.from(document.querySelectorAll('.expanding-field')).forEach(field => {
field.addEventListener('keyup', onFieldChange);
});
}
function onFieldChange(e) {
let field = e.target,
len = field.value.length;
field.style.width = (len * 0.667) + 'em';
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" class="expanding-field" name="name1" id="nametf" value="" required>
</form>
Try this:
var nametf = document.getElementById("nametf");
nametf.addEventListener("input", function(){
if(nametf.value.length > 17) {
nametf.size = "30";
} else {
nametf.size = "20";
}
});
#nametf {
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" size="20" value="" required>
</form>
This question already has answers here:
How do I detect a click outside an element?
(91 answers)
Closed 3 years ago.
I had created a sample check boxes dropdown, I facing an issue in hiding the dropdown by clicking outside the dropdwon. Below is the code
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
$('#checkboxes').click(function(e) {
e.stopPropagation();
});
$(document).click(function() {
$('#checkboxes').style.display = "none";
});
.category {
width: 250px;
}
#checkboxes {
width: 250px;
display: none;
border: 1px #aaa solid;
overflow-y: scroll;
background-color: white;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #bbb;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="category" onclick="showCheckboxes()">
<option value="">Select cities
</option>
</select>
<div id="checkboxes">
<label>
<input type="checkbox" /> Bangalore
</label>
<label>
<input type="checkbox" /> Hyderabad
</label>
<label>
<input type="checkbox" /> Delhi
</label>
<label>
<input type="checkbox" /> Mumbai
</label>
<label>
<input type="checkbox" /> Chennai
</label>
<label>
<input type="checkbox" /> Panaji
</label>
</div>
I want the drop down to get close by clicking outside any where. kindly help me on this i tried the script to make the display style none, but its not working
style is a property on HTMLElement, it is not available on jQuery. You should use .css() on jQuery object:
Change
$('#checkboxes').style.display = "none";
To
$('#checkboxes').css("display","none");
Though I prefer using show()/hide() instead of setting the style property.
You can check the event.target.nodeName to show()/hide() the element.
Try the following way:
function showCheckboxes() {
if ($('#checkboxes').is(':visible')) {
$('#checkboxes').hide();
}
else {
$('#checkboxes').show();
}
}
$(document).click(function(e) {
if(e.target.nodeName == 'BODY')
$('#checkboxes').hide();
});
.category {
width: 250px;
}
#checkboxes {
width: 250px;
display: none;
border: 1px #aaa solid;
overflow-y: scroll;
background-color: white;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #bbb;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="category" onclick="showCheckboxes()">
<option value="">Select cities
</option>
</select>
<div id="checkboxes">
<label >
<input type="checkbox" /> Bangalore
</label>
<label>
<input type="checkbox" /> Hyderabad
</label>
<label>
<input type="checkbox" /> Delhi
</label>
<label>
<input type="checkbox" /> Mumbai
</label>
<label>
<input type="checkbox" /> Chennai
</label>
<label>
<input type="checkbox" /> Panaji
</label>
</div>
Alternatively you can try multi Select dropDownList with check Boxes using jQuery plugin as explain here MultiSelect DropDownList With CheckBoxes In ASP.Net With C# And VB.NET Using jQuery Plugin
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.
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>