Multiple checkbox can't access from JavaScript function - javascript

I have dynamic multiple check boxes which is used to restore multiple files. It works perfectly when I have more than 1 check boxes. Here is my php code for check boxes:
<form name="RestoreFile">
<input type="checkbox" title="'.$FldDoc['FldDocumentName'].'" name="restore_checkbox" value="'.$FldDoc['FldDocumentID'].'" id="restore_'.$NodeId.'_'.$FldDoc['FldDocumentID'].'"/>
<input type="button" value="Restore" onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);" />
</form>
And the definition of function RestoreDocFile() is given below:
function getSelected(opt)
{
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if (opt[intLoop].checked)
{
index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}
function RestoreDocFile(nodeid, opt)
{
var getSelectDocIds = getSelected(opt);
//alert(nodeid+','+getSelectDocIds);
var strSelectedDocIds = "";
var i=0;
for (var item in getSelectDocIds)
{
if(i!=0)
{
strSelectedDocIds+=":";
}
strSelectedDocIds += getSelectDocIds[item].value ;
i++;
}
}
The problem is that if there has 1 checkbox at the time of form load it doesn't work properly.

Try replacing
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);"
with
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.getElementsByName(\'restore_checkbox\'));"
This will ensure you get a NodeList regardless of how many checkboxes there are.

Related

How to store all checked items from a list into the local storage. (Javascript)

I have a list whit a dynamically created checkbox inputs and when the list is done and you finish using it, I want to store the checked items from the list to the localstorage.
(I need to store only the checked items when the save button is pressed.)
HTML:
<template id = "index.html">
<ons-page id=tab1>
<div id="listac">LISTA</div>
<ons-list id="products">
<!-- HERE IS WHERE I ADD THE CHECKBOX ITEMS-->
</ons-list>
<ons-speed-dial position="bottom right" direction="left">
<ons-fab>
<ons-icon icon="fa-cog"></ons-icon>
</ons-fab>
<ons-speed-dial-item ONCLICK="savefunction()"> <!--THIS IS THE BUTTON THAT "SAVES".-->
<ons-icon id = "consolidar" icon="fa-cart-arrow-down"></ons-icon>
</ons-speed-dial-item>
<ons-speed-dial-item >
<ons-icon id = "anadir" icon="fa-plus" ></ons-icon>
</ons-speed-dial-item>
</ons-speed-dial>
</ons-page>
</template>
Js:
function add_checkbox_item(){
var product = document.getElementById('addirp').value;
var text_product = document.createTextNode(product);
var checkbox_product = document.createElement('ons-checkbox')
checkbox_product.appendChild(text_product);
var finall_product = document.createElement('ons-list-item');
finall_product.appendChild(checkbox_product);
finall_product.classList.add("products");
document.getElementById('productos').appendChild(finall_product);
dialog = document.getElementById('dialog1');
dialog.hide();
};
function savefunction(){
// HERE IS WHERE I START GETTING LOST
var checkedValue = null;
var inputElements = document.getElementsByClassName('products');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
}
What you need to do, is to query all the checkbox elements and iterate through them. Your code currently selects the ons-list-item elements instead of the checkboxes.
First, start by making the function select the correct elements:
function savefunction(){
var checkboxes = document.querySelectorAll('.products'); // <-- select the checkboxes
for (var i = 0; i < checkboxes.length; i += 1) { // <-- iterate
if (checkboxes[i].checked) {
// store values
} else { // <-- this branch is optional (I don't know if you need it)
// remove previously stored values
}
}
}
As you can see, I also added an else branch, in case you also want to remove a previously stored value when the user unchecks a previously checked checkbox. However, if you don't need it, just remove the else branch.
From here on, you have two possibilities: You can either store each checked checkbox separately into the localStorage, or you can store a list of all the checked checkboxes.
Each box separately (remember to remove the else branch if you don't need it)
function savefunction(){
var checkboxes = document.querySelectorAll('.products');
for (var i = 0; i < checkboxes.length; i += 1) {
if (checkboxes[i].checked) {
localStorage.setItem(checkbox[i].name, checkbox[i].value); // <-- stores a value
} else {
if (localStorage.getItem(checkbox[i].name)) { // <-- check for existance
localStorage.removeItem(checkbox[i].name); // <-- remove a value
}
}
}
}
A list of all boxes
function savefunction(){
var checkboxes = document.querySelectorAll('.products');
var checked = {};
for (var i = 0; i < checkboxes.length; i += 1) {
if (checkboxes[i].checked) {
checked[checkbox[i].name] = checkbox[i].value;
}
// <-- no need for else, because we simply override
}
localStorage.setItem('checked_boxes', JSON.stringify(checked)); // <-- localStorage can only store `String` values
}
When using the second approach, don't forget to call JSON.parse on the stored values when you want to use them (this is just for demo purposes):
function restoreCheckboxes (checkboxElements) {
var checkboxStates = localStorage.getItem('checked_boxes'),
i;
if (checkboxStates) {
checkboxStates = JSON.parse(checkboxStates); // <-- parse string to object
for (i = 0; i < checkboxElements.length; i += 1) {
if (checkboxStates.hasOwnProperty(checkboxElements[i].name)) {
checkboxElements[i].checked = true;
}
}
}
}
Another point is this: Do you want to persist that information between different sessions or just as long as the current session is active? If the latter is true, consider using sessionStorage instead of localStorage. You can read about their differences on MDN
This code will exactly be working.
Make unique the checkboxes with name parameters.
On-click call function
First function to store the values and second function to restore the values from local storage
function savefunction(){
var checkboxes = document.querySelectorAll('.products');
var checked = {};
for (var i = 0; i < checkboxes.length; i += 1) {
if (checkboxes[i].checked) {
checked[checkboxes[i].name] = checkboxes[i].value;
}
// <-- no need for else, because we simply override
}
localStorage.setItem('checked_boxes', JSON.stringify(checked)); // <-- localStorage can only store `String` values
}
function restoreCheckboxes () {
var checkboxElements = document.querySelectorAll('.products');
var checkboxStates = localStorage.getItem('checked_boxes');
if (checkboxStates) {
checkboxStates = JSON.parse(checkboxStates); // <-- parse string to object
for (i = 0; i < checkboxElements.length; i += 1) {
if (checkboxStates.hasOwnProperty(checkboxElements[i].name)) {
checkboxElements[i].checked = true;
}
}
}
}
<body onload="restoreCheckboxes()">
<div class="box1">
<div class="box2">
iWork for iColud
</div>
<div class="box3">
<input type="checkbox" name="bixby1" onclick="savefunction()" class="products">
</div></div>
<div class="box1">
<div class="box2">
iWork for iColud
</div>
<div class="box3">
<input type="checkbox" name="bixby2" onclick="savefunction()" class="products">
</div></div>
<div class="box1">
<div class="box2">
iWork for iColud
</div>
<div class="box3">
<input type="checkbox" name="bixby3" onclick="savefunction()" class="products">
</div></div>
</body>

Angularjs checkbox value on edit profile page

I am new to angularjs and getting some problem on checkbox values on edit profile page.
I have an array for checkbox
$scope.checkBoxes = [
{id:'1', value:'Reading'},
{id:'2', value:'Cooking'},
{id:'3', value:'Dancing'},
{id:'4', value:'Singing'}
];
and I have used ng-repeat for showing checkbox
<div ng-repeat="checkBox in checkBoxes" style="display:inline;">
<input type="checkbox" ng-model="checkBox.selected" id={{checkBox.id}}' ng-checked="checkItem(checkBox.id)" ng-change="listActionsHandler(checkBoxes)">{{ checkBox.value }}
</div>
This is my ng-change function:
$scope.listActionsHandler = function(list) {
var has = [];
angular.forEach(list, function(item) {
if ( angular.isDefined(item.selected) && item.selected === true ) {
has.push(item.id);
}
});
formData['hobby'] = has;
}
and this is my ng-checked function that is used for showing checkbox checked according to database saved value.
var arr_checked_items = data.data.hobby;
var arraySize = arr_checked_items.length;
$scope.checkItem = function (id) {
var checked = false;
for(var i=0; i<= arraySize; i++) {
if(id == arr_checked_items[i]) {
checked = true;
}
}
return checked;
};
These function work properly on add and edit page, but problem is that when I doesn't apply any changes on checkbox and click on submit button it take blank value.
My question is that: if I does not apply any changes, it should take old value of checkbox and if I apply any changes, it should take new value of checkbox.
Please try with below code. I am not sure weather it is working or not.
$scope.checkItem = function (id) {
var checked = "";
for(var i=0; i<= arraySize; i++) {
if(id == arr_checked_items[i]) {
checked = "checked";
}
}
return checked;
};

Run function on every table entry

I got a table that has an entry that looks like this:
<tr>
<td><input type="checkbox" name="ids[]"/><a style="cursor: pointer;" onclick="addtopath('parameter1', 'parameter2')" class="btn_addpath"> Add</a></td>
</tr>
As you can see every table entry countains the function "addtopath('parameter1', 'paramter2');"
The parameters are generated via php; so each item is different. Also, every entry has a checkbox. This is where the trouble occurs.
I want to create a function that runs the "addtopath" function for every table item, that is checked, as if the user clicked the "Add" button.
Hope it makes sense.
Modern browsers...
function runChecked() {
var links = mytable.querySelectorAll("input[name='ids[]']:checked + a.btn_addpath");
[].forEach.call(links, function(link) {
link.onclick();
});
}
IE8+...
function runChecked() {
var inputs = mytable.querySelectorAll("input[name='ids[]']");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
inputs[i].nextSibling.onclick();
}
}
IE6+...
function runChecked() {
var inputs = mytable.getElementsByTagName("input");
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].name === "ids[]" && inputs[i].checked)
inputs[i].nextSibling.onclick();
}
}
I would add the parameters to data attributes in case you want to move to jQuery at some point. It's also good practice.
<td><input type="checkbox" data-one="one" data-two="two" class="btn_addpath"/>Add</td>
<td><input type="checkbox" data-one="three" data-two="four" class="btn_addpath"/>Add</td>
<td><input type="checkbox" data-one="five" data-two="six" class="btn_addpath"/>Add</td>
<td><input type="checkbox" data-one="seven" data-two="eight" class="btn_addpath"/>Add</td>
function addToPath(p1, p2) {
console.log(p1, p2);
}
var checkboxes = document.getElementsByClassName('btn_addpath');
var checkboxArr = [].slice.call(checkboxes);
checkboxArr.forEach(function (el) {
var p1 = el.getAttribute('data-one');
var p2 = el.getAttribute('data-two');
el.onchange = function () {
if (this.checked) { addToPath(p1, p2); }
};
});
If you use jQuery you can use the following code:
$("input[type=checkbox]:checked").siblings('a').click();
Test it at http://jsfiddle.net/tMe46/
This should emulate onClick event at all links in checked boxes
$("input[type=checkbox]:checked + a").click();

Cannot get values of all my checkboxes on a click event in Javascript

I have a list of checkbox as below :
The code for that list is :
#foreach (extranetClient.Models.Classes.FonctionContact fonction in ViewBag.Fonctions)
{
string coche = "";
if ((#Model.ListeFonctions).Any(c => c.IdFonction == fonction.IdFonction))
{
coche = "checked";
}
<input type="checkbox" #coche id="checkbox" value="#fonction.IdFonction" />#fonction.LibelleFonction <br />
}
So now I would like to get the values of all the ckeckboxes which are checked in the list everytime I check one of them. So I've tried that :
$("#checkbox").click(function () {
var TabIdFonctions = new Array();
var compteur = 1;
$("input[type='checkbox']:checked").each(
function () {
TabIdFonctions[compteur] = $(this).val();
compteur++;
});
});
But it doesn't work and I don't really know why. Hope somebody has an idea.
In javascript arrays are 0 indexed. But you could use the .push method instead. Also you should use a class selector, not an id selector because you can have only one element with a given id:
$('.checkbox').click(function () {
var TabIdFonctions = new Array();
$('.checkbox:checked').each(function () {
TabIdFonctions.push($(this).val());
});
});
Also don't forget to give your checkboxes a class, not id:
<input type="checkbox" #coche class="checkbox" value="#fonction.IdFonction" />
javascript code
var els = document.getElementsByTagName('input');
for (var i = 0; i < els.length; i++) {
var el = els[i];
if (el.checked == true) {
TabIdFonctions.push(el.value);
}
}

Need help with javascript unchecking of one checkbox unchecks the main checkbox

I have a table that has a header with a checkbox in that row. The data gets dynamically added in the table with javascript. Now checking on the checkbox that is in the header row checks or unchecks all the checkboxes of all rows.. I have done it till here in the method "checkUncheck()", i.e.:
<input type="checkbox" id="chkAppId" onclick="checkUncheck()"/>
But now, suppose there are 10 records dynamically added in the table. I have checked the main checkbox in the header. After that, I uncheck one of the checkboxes, e.g.: on the 10th row, then the checkbox of the header must be unchecked....and if I check all of the 10 rows of checkboxes manually, then the checkbox of main header must be checked. This is something normally observed in Yahoo, gmail, etc...
One way would be to count the number of checked ones and compare it with the total number of rows, and if found equal, then check the main one; otherwise, uncheck the main one. But I can't figure out where to do that... not working!
Update
<html>
<head><title>Checkbox puzzle</title></head>
<body>
<input type="checkbox" id="chkAppId" onclick="checkUncheck()"/>Main<br/>
<input type="checkbox" id="chkAppId1" onclick="check()"/>chk1<br/>
<input type="checkbox" id="chkAppId2" onclick="check()"/>chk2<br/>
<input type="checkbox" id="chkAppId3" onclick="check()"/>chk3<br/>
<script type="text/javascript">
function checkUncheck()
{
var totalRows = 4;
if(document.getElementById("chkAppId").checked){
checkedAll = true;
}
else{
checkedAll = false;
}
for(i = 1; i< totalRows; i++){
document.getElementById("chkAppId"+i).checked = checkedAll;
}
}
function check()
{
var totalRows = 4,count=0;
for(i = 1; i< totalRows; i++) {
if(document.getElementById("chkAppId"+i).checked){
count= count+1;
}
}
if(count ==totalRows - 1){
//alert("check Main");
document.getElementById("chkAppId").checked = true;
}
else
{
//alert("uncheck Main");
document.getElementById("chkAppId").checked = false;
}
}
</script>
</body>
</html>
This would be a simpler version that can explain the purpose, for anyone else who may need to implement such things.
When you dynamically insert the checkboxes, do you give them each different IDs?
Post the code you have and someone may be able to help you.
Here's a self-contained example with 'dynamic' rows.
<HTML>
<input type="button" value="add row" onclick="add_row()">
<table border id="my_table">
<TR><TH><input type="checkbox" onclick="header_check_click()" id="header_check"></TH><TH>HEADER</TH></TR>
</table>
<FORM name="frm">
<script language="javascript">
var g_check_ids = [];
function header_check_click()
{
var header_check = document.getElementById("header_check");
for (var k in g_check_ids)
{
var the_check = document.getElementById("check" + g_check_ids[k]);
the_check.checked = header_check.checked;
}
}
function fix_header_checkbox()
{
var all_checked = true;
for (var k in g_check_ids)
{
var the_check = document.getElementById("check" + g_check_ids[k]);
if (!the_check.checked)
{ all_checked = false;
}
}
var header_check = document.getElementById("header_check");
header_check.checked = all_checked;
}
function add_row()
{
var tbl = document.getElementById("my_table");
var cnt = tbl.rows.length;
var row = tbl.insertRow(cnt);
var checkCell = row.insertCell(0);
checkCell.innerHTML = "<input onclick=\"fix_header_checkbox()\" type=\"checkbox\" id=check" + cnt + ">";
g_check_ids.push(cnt);
var txtCell = row.insertCell(1);
txtCell.innerHTML = "Cell " + cnt;
fix_header_checkbox();
}
add_row();
</script>
</FORM>
</HTML>

Categories

Resources