I have 4 checkboxes. I add values of them to an array on check. It looks like this.
Here are the four checkboxes I have.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
Once I check all four of them, the array becomes,
["degree", "pgd", "hnd", "advdip"]
When I uncheck a checkbox, I need to remove the value of it from the array according to its correct index number. I used splice() but it always removes the first index which is degree. I need to remove the value from the array according to its index number no matter which checkbox I unselect. Hope someone helps. Below is the code. Thanks in advance!
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = $(this).index();
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
You used the wrong way to find index in your code. If you used element index, it will avoid real index in your array and gives the wrong output. Check below code, it may be work for you requirement.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = selectedValues.indexOf(this.value);
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
Add change handler to the inputs and use jQuery map to get the values of the checked inputs.
var levels
$('#checkArray input').on('change', function () {
levels = $('#checkArray input:checked').map(function () {
return this.value
}).get()
console.log(levels)
}).eq(0).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
my approach was to add an event handler that reads all checked values when any of those inputs is clicked and empty the array before loging the response. no need to add any dependencies with this one
Hope this is what you are looking for
function getLevels() {
let checkboxContainer = document.getElementById("checkboxContainer");
let inputs = checkboxContainer.querySelectorAll("input");
let checked = [];
inputs.forEach( (input) => {
checked = [];
input.addEventListener( 'click', () => {
checked = [];
inputs.forEach( (e) => {
e.checked ? checked.push(e.value) : null;
})
console.log(checked);
});
});
}
getLevels();
<div id="checkboxContainer">
<input type="checkbox" value="degree" >
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</div>
I don't know if this is what you need, to show an array of the selected values, if you want you can call the function that calculates on the check.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
<button onclick="getLevels()">getLevels</button>
<script>
function getLevels() {
var levels = [];
$.each($("input:checked"), function() {
levels.push(($(this).val()));
});
console.log(levels);
}
getLevels();
</script>
Related
I have multiple checkboxes added with a button. I want to assign a value of 150 for each checkbox that is checked. Maybe my logic is wrong, but i cant get it working. Ideas?
function getValues() {
var cost = 0;
var isChecked = $('.isLab').prop('checked');
$('.isLab').each(function () {
if (isChecked == true) {
cost = 150
}
});
alert(cost);
}
$('button').click(getValues);
function getValues() {
alert( $('.isLab:checked').length * 150 );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="isLab"/> Item 1<br/>
<input type="checkbox" class="isLab"/> Item 2<br/>
<input type="checkbox" class="isLab"/> Item 3<br/>
<button>Get values</button>
Comments inline...
function getValues() {
var cost = 0;
$('.isLab').each(function (index, element) {
if (element.checked == true) { // reference current checkbox
cost += 150; // ADD to it!
}
});
alert(cost);
}
I have a form with checkboxes. The javascript function allPosPlayersCheckboxes utilizes a "Check All" Checkbox that controls the others. The other functions (getPosAllFilterOptions & getPosPlayersFilterOptions) push the "name" properties into an array. This all is triggered when anything is changed on the form.
Suppose that all checkboxes are unchecked. If the user checks the "nonP_all" checkbox, it will automatically check the other checkboxes with class="nonP". Unfortunately, when the "name" properties are pushed into the array, it will not include any with class="nonP".
I"m unsure why they are not included in the array. Are the functions (getPosAllFilterOptions & getPosPlayersFilterOptions) not waiting for allPosPlayersCheckboxes to complete? Is there a way to have the secondary checkboxes included in the arrays? Thanks for any help!
<form id="formFilter">
<h2>Filter options</h2>
<div>
<input type="checkbox" id="nonP_all" class="Pos_all" name="nonP" checked="checked">
<label for="nonP">Position Players</label>
<input type="checkbox" id="C" class="nonP" checked="checked" name="C">
<label for="C">C</label>
<input type="checkbox" id="1B" class="nonP" checked="checked" name="1B">
<label for="1B">1B</label>
<input type="checkbox" id="2B" class="nonP" checked="checked" name="2B">
<label for="2B">2B</label>
<input type="checkbox" id="3B" class="nonP" checked="checked" name="3B">
<label for="3B">3B</label>
<input type="checkbox" id="SS" class="nonP" checked="checked" name="SS">
<label for="SS">SS</label>
<input type="checkbox" id="LF" class="nonP" checked="checked" name="LF">
<label for="LF">LF</label>
<input type="checkbox" id="CF" class="nonP" checked="checked" name="CF">
<label for="CF">CF</label>
<input type="checkbox" id="RF" class="nonP" checked="checked" name="RF">
<label for="RF">RF</label>
<input type="checkbox" id="DH" class="nonP" checked="checked" name="DH">
<label for="DH">DH</label>
</div>
function allPosPlayersCheckboxes(){
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
};
function getPosAllFilterOptions(){
var pos_all_opts = new Array();
$(".Pos_all:checked").each(function(){
pos_all_opts.push($(this).attr('name')); // places names into array
});
return pos_all_opts;
}
function getPosPlayersFilterOptions(){
var nonP_opts = new Array();
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
return nonP_opts;
}
var $formFilter = $("#formFilter");
$formFilter.change(function(){
allPosPlayersCheckboxes();
var pos_all_opts = getPosAllFilterOptions();
var nonP_opts = getPosPlayersFilterOptions();
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
The reason that you are having an issue is because the checking of the boxes event is being caught at the form change event handler, and the code that checks and unchecks all of the other boxes hasn't executed yet. As a result when you call your functions, the count for checked boxes is 0. This also happens when you uncheck one of the position checkboxes, eventually the pos_all_opts variable gets out of sync and is incorrect as well.
These click handlers don't need to be in a function. They are handlers that are hooked into the behavior of your checkboxes.
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
This is probably a little less than ideal, but it works. The code that was in the functions to build the arrays has been moved into the change handler for the form.
$("#formFilter").change(function(event){
var pos_all_opts = [];
var nonP_opts = [];
if(event.target === $("#nonP_all")[0] && event.target.checked) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else if(event.target === $("#nonP_all")[0] && !event.target.checked) {
pos_all_opts = [];
nonP_opts = [];
} else if(event.target !== $("#nonP_all")[0] && $(".nonP:checked").length === 9) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else {
pos_all_opts = [];
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
}
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
Fiddle for reference
how to pass checkbox values in an array to a function using onclick in JavaScript.
following is my html code. Note that I don't use form tag. only input tags are used.
<input id="a"name="a" type="checkbox" value="1" checked="checked" >A</input>
<input id="a"name="a" type="checkbox" value="2" checked="checked" >B</input>
<input id="a"name="a" type="checkbox" value="3" checked="checked" >C</input>
<button onclick="send_query(????)">CLICK</button>
following is my JavaScript function
function send_query(check) {
var str = "";
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
str = str + check[i];
}
console.log(str);
}
You can write a onclick handler for the button, which can create an array of clicked checkbox values and then call the send_query with the parameter as shown below
<button onclick="onclickhandler()">CLICK</button>
then
function onclickhandler() {
var check = $('input[name="a"]:checked').map(function () {
return this.value;
}).get();
console.log(check);
send_query(check)
}
Note: I would also recommend using jQuery to register the click handler instead of using inline onclick handler.
Note: Also ID of elements must be unique in a document... you have multiple elements with id a, I'm not seeing you using that id anywhere so you could probably remove it
With pure javascript (demo) (tested with Chrome only).
HTML :
<button onclick="send_query(document.getElementsByTagName('input'))">
Javascript :
function send_query(check) {
var values = [];
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
values.push(check[i].value);
}
}
console.log(values.join());
}
Try this
<form name="searchForm" action="">
<input type="checkbox" name="categorySelect[]" id="1"/>
<input type="checkbox" name="categorySelect[]" id="2" />
<input type="checkbox" name="categorySelect[]" id="3"/>
<input type="button" value="click" onclick="send_query();"/>
</form>
JS
function send_query() {
var check = document.getElementsByName('categorySelect[]');
var selectedRows = [];
for (var i = 0, l = check.length; i < l; i++) {
if (check[i].checked) {
selectedRows.push(check[i]);
}
}
alert(selectedRows.length);
}
I'm trying to get this thing work for a while but I guess I need to tweak the code from somewhere. I thought, someone here could better guide me instead of banging my head to my coding screen :)
here's the actual process:
<input type="hidden" name='oneSelectionChk_1'>
<input type="checkbox" name='awp_group_1' id='id1'>
<input type="checkbox" name='awp_group_1' id='id2'>
<input type="checkbox" name='awp_group_1' id='id3'>
<input type="checkbox" name='awp_group_1' id='id4'>
<input type="hidden" name='oneSelectionChk_2'>
<input type="checkbox" name='awp_group_2' id='id5'>
<input type="checkbox" name='awp_group_2' id='id6'>
<input type="checkbox" name='awp_group_2' id='id7'>
<input type="checkbox" name='awp_group_2' id='id8'>
<input type="hidden" name='oneSelectionChk_3'>
<input type="checkbox" name='awp_group_3' id='id9'>
<input type="checkbox" name='awp_group_3' id='id10'>
<input type="checkbox" name='awp_group_3' id='id11'>
<input type="checkbox" name='awp_group_3' id='id12'>
what I'm using for jQuery is:
var chkFields = $("input[name='oneSelectionChk']");
$.each(chkFields, function(i, field){
var groupID = field.id.split('_'); // Getting the ID of the group
var chkGroupBoxes = $('input[name="awp_group_"'+groupID[1]);
if(field.value==1)
{
//$.each(chkGroupBoxes, function(j, thisChkBox){
//alert(thisChkBox.value + " #"+j);
alert( $('input[name="awp_group_"'+groupID[1]).filter(':checked').length);
if($('input[name="awp_group_"'+groupID[1]+':checked').length > 0 )
{
//$.scrollTo( '#awp_container', 1200 );
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Selected ");
//alert( "Class AlertMsgText Should be removed Now");
$("#selectInstruction_"+groupID[1]).removeClass("AlertMsgText");
//return
}
else
{
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Still not selected ");
//alert("Please select atleat 1 from Option #"+groupID[1]);
$("#selectInstruction_"+groupID[1]).addClass("AlertMsgText");
$.scrollTo( '#awp_container', 1200 );
//return;
}
//});
}
});
This code always giving me 0 length of checkboxes, I'm not sure if I need to loop through again for each checkbox or this might work?
Any quick help should be appreciated!
Try
var chkFields = $('input[name^="oneSelectionChk"]');
$.each(chkFields, function (i, field) {
var groupID = field.name.replace('oneSelectionChk_', '')
var chkGroupBoxes = $('input[name="awp_group_' + groupID + '"]');
if (chkGroupBoxes.filter(':checked').length == 0) {
alert('please select at least one checkbox under: ' + field.name)
}
});
Demo: Fiddle
There is no element with name attribute of oneSelectionChk in your markup, the hidden inputs have name attributes that start with oneSelectionChk, you have to use attribute starts with selector.
In case that elements are siblings you can select the target elements using .nextUntil() method:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]');
$hidden.each(function(){
var $chekboxes = $(this).nextUntil('input[type=hidden]'),
$checked = $checkboxes.filter(':checked'),
$unchecked = $chekboxes.not($checked);
});
Using name attributes:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]'),
$checkboxes = $('input[type=checkbox]');
$hidden.each(function() {
var n = this.name.split('_')[1];
var $grp = $checkboxes.filter('[name="awp_group_'+ n +'"]');
// ..
});
I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.