I am trying to build a little web app using local storage. I can add and delete items . I want to add new item to local storage but I always fail. When i try to add a new item it always show "no localStorage in window".
So I edit it (still not works) :
function addStorage() {
var key = document.getElementById('storageKey');
var data = document.getElementById('storageData');
var nic = document.getElementById('storageNic');
//localStorage setItem
if ("localStorage" in window) {
localStorage.setItem(key.value, data.value, nic.value);
location.reload();
} else {
alert("no localStorage in window");
}
function removeStorage() {
var key = document.getElementById('removeKey');
//localStorage removeItem
if ("localStorage" in window) {
if (localStorage.length > 0) {
localStorage.removeItem(key.value);
location.reload();
}
} else {
alert("no localStorage in window");
}
}
function clearStorage() {
//localStorage clear
if ("localStorage" in window) {
if (localStorage.length > 0) {
localStorage.clear();
location.reload();
}
} else {
alert("no localStorage in window");
}
}
window.onload = function () {
var localhtml = "";
//localStorage key and getItembr
for (var i = 0; i < localStorage.length; i++) {
localhtml += "<li>" + localStorage.key(i) + " " + localStorage.getItem(localStorage.key(i)) + "</li>";
}
document.getElementById('localStorageData').innerHTML = localhtml;
}
}
HTML:
<script>
function addTextTag(text){
document.getElementById('storageKey').value += text;
}
</script>
<input type="text" id="storageKey">
<input type="text" id="storageData">
<input type="text" id="storageNic">
<input type="button" id="save" value="SAVE" onclick="addStorage();return false;">
<input type="button" id="clear" value="Clear" onclick="clearStorage(); return false;">
<div id="localStorageData"></div>
Given that localStorage isn't defined in window, your browser probably doesn't support it. See Mozilla's browser compatibility matrix for reference.
I've concocted a jsFiddle for you try:
HTML
<input id="storageKey" value="key"></input>
<input id="storageData" value="value"></input>
<input id="storageNic" value="nic"></input>
<div id="localStorageData"></div>
JavaScript
function addStorage() {
console.log("Add storage");
var key = document.getElementById('storageKey');
var data = document.getElementById('storageData');
var nic = document.getElementById('storageNic');
//localStorage setItem
if ("localStorage" in window) {
console.log("Setting item " + key.value + " to " + data.value +
" in localStorage");
localStorage.setItem(key.value, data.value, data.
} else {
alert("no localStorage in window");
}
}
function removeStorage() {
var key = document.getElementById('removeKey');
//localStorage removeItem
if ("localStorage" in window) {
if (localStorage.length > 0) {
localStorage.removeItem(key.value);
location.reload();
}
} else {
alert("no localStorage in window");
}
}
window.onload = function () {
console.log("onLoad");
var localhtml = "";
addStorage();
//localStorage key and getItembr
for (var i = 0; i < localStorage.length; i++) {
localhtml += "<li>" + localStorage.key(i) + " " +
localStorage.getItem(localStorage.key(i)) + "</li>";
}
document.getElementById('localStorageData').innerHTML = localhtml;
};
If you try this fiddle, you should see a list of localStorage items. It works for me (Chrome 33.0.1750.117 m).
Related
So I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText".
<script type="text/javascript">
function textToDisplay (radioValue) {
console.log("textToDisplay + " + radioValue);
var displayText = "";
if (radioValue == "S") {
displayText = "Shortboards are under 7 ft in length.";
}
else if (radioValue == "L") {
displayText = "Longboards are usually between 8 and 10 ft.";
}
if (radioValue == "A") {
displayText = "Alternative boards defy easy aesthetic description.";
}
if (radioValue == "M") {
displayText = "Mid-Length surfboards are between 7 and 8 ft.";
}
return (displayText)
}
//DOM modification
function modifyDom(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
console.log(node);
var insertnode = document.getElementById("radioButtons");
var infonode = document.getElementById("info")
if (infonode === null) {
console.log("infonode does not yet exist");
var node = document.createElement("DIV");
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
console.log(node);
insertnode.appendChild(node);
}
else {
console.log("infonode already exists");
infonode.innerHTML = displayText;
}
}
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
var cbSelected = 0;
for (i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
cbSelected += 1;
}
}
if (cbSelected < 2) {
return (errorString);
} else {
return "";
}
}
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.extras, "At least TWO fin setup needs
to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
When I reset my page using the button,
<input type="reset" name="reset" value="Reset">
the buttons themselves are cleared but the information that appeared from selecting the button is still visible. How can I reset the page so the displayText information is not visible? Thanks!
You can use an event listener for the reset event generated by clicking the reset button to execute cleanup code.
Here's a cut down example of the technique:
"use strict";
let myForm = document.getElementById("myForm");
let infoNode = document.getElementById("infonode");
let infoText = {
"S": "small board's are good",
"L": "large board's are good too"
};
myForm.addEventListener("change", function (event) {
if(event.target.name == "size") {
infoNode.innerHTML = infoText[ event.target.value];
}
}, false);
myForm.addEventListener("reset", function (event) {
infoNode.innerHTML = "";
}, false);
<form id="myForm">
<label> <input name="size" type="radio" value = "S"> Short</label><br>
<label> <input name="size" type="radio" value = "L"> Long</label><br>
<input type="reset" value="reset">
</form>
<div id="infonode"></div>
would suggest to remove the dynamically attached div#info:
document.getElementById("info").remove();
or blank it:
document.getElementById("info").innerHTML = "";
I created a Chicago employee search index and wanted to create an alert when there are no matching records found, but can't seem to be able to find out what value I need to put in for when it's empty. Ideally, when the function get's submitted and no results are found, it would push an alert onto the screen indicating no matching records found.
The alert right now is located in the submit function in the last bit of code posted
ChicagoEmployeesQuery = function(searchKey) {
var url,
url =
"https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json" +
"?search=key_word&jsonp=?";
this.query = url.replace("key_word", searchKey);
}
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
var i, results;
results = [];
for (i = 0; i < response.data.length; i += 1) {
row = {
name: response.data[i][8],
title: response.data[i][9],
department: response.data[i][10],
salary: response.data[i][14]
}
results.push(row);
}
callBack(results);
})
}
<!doctype html>
<html>
<head>
<title>Salary Info Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="ChicagoEmployees.js"></script>
<script src="demoLS.js"></script>
</head>
<body>
<h1>Salary Info</h1>
<p>Enter first or last name: <input type="text" id="key-word" size="20" /></p>
<p><input type="button" id="start" value="Submit Query for name and Salary" /></p>
<p><input type="button" id="start2" value="Submit Query for Names and Departments" </p>
<h2>First Matching Employing + Salary</h2>
<div id="result">
First result appears here
</div>
<h2>List of All Matching Names</h2>
<div id="names">
All Matching Names Appear Here
</div>
<h2>List of All Matching Names + Departments</h2>
<div id="namesDepartment">
All Matching Names + Departments Appear Here
</div>
</body>
</html>
// Use with demo.html
// Tested with jQuery 3.1.1, January 2017
// Updated January 2018
// This function is called when the response has returned
postResult = function(list) {
//var nameList, i, glist;
glist = list;
if (list.length > 0) {
$("#result").html(list[0].name + "<br />" + list[0].salary);
}
nameList = "";
for (i = 0; i < list.length; i += 1) {
nameList = nameList + list[i].name + "<br />";
}
$("#names").html(nameList);
}
postResult2 = function(list) {
//var namesDepartmentList, i, glist;
glist = list;
if (list.length > 0) {
$("#namesDepartment").html(list[0].name + "<br />" + list[0].department);
}
namesDepartmentList = "";
for (i = 0; i < list.length; i += 1) {
namesDepartmentList = namesDepartmentList + list[i].name + "<br/>" + list[i].department + "<br />";
}
$("#namesDepartment").html(namesDepartmentList);
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#result").html("waiting...");
query.getList(postResult);
if (searchKey.isEmpty()) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
}
submit2 = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#namesDepartment").html("waiting...");
query.getList(postResult2);
console.log("A result should appear now!");
}
$(function() {
$("#start").click(submit);
});
$(function() {
$("#start2").click(submit2);
});
If I understand your question correctly, you can check if there's any matching data at the end of the getlist()
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
// ... codes ...
callBack(results);
// like this
if (response.data.length==0) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
})
}
// Use with demo.html
// Tested with jQuery 3.1.1, January 2017
// Updated January 2018
// This function is called when the response has returned
postResult = function(list) {
//var nameList, i, glist;
glist = list;
if (list.length > 0) {
$("#result").html(list[0].name + "<br />" + list[0].salary);
}
nameList = "";
for (i = 0; i < list.length; i += 1) {
nameList = nameList + list[i].name + "<br />";
}
$("#names").html(nameList);
}
postResult2 = function(list) {
//var namesDepartmentList, i, glist;
glist = list;
if (list.length > 0) {
$("#namesDepartment").html(list[0].name + "<br />" + list[0].department);
}
namesDepartmentList = "";
for (i = 0; i < list.length; i += 1) {
namesDepartmentList = namesDepartmentList + list[i].name + "<br/>" + list[i].department + "<br />";
}
$("#namesDepartment").html(namesDepartmentList);
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#result").html("waiting...");
query.getList(postResult);
}
submit2 = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#namesDepartment").html("waiting...");
query.getList(postResult2);
console.log("A result should appear now!");
}
$(function() {
$("#start").click(submit);
});
$(function() {
$("#start2").click(submit2);
});
ChicagoEmployeesQuery = function(searchKey) {
var url,
url =
"https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json" +
"?search=key_word&jsonp=?";
this.query = url.replace("key_word", searchKey);
}
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
var i, results;
results = [];
for (i = 0; i < response.data.length; i += 1) {
row = {
name: response.data[i][8],
title: response.data[i][9],
department: response.data[i][10],
salary: response.data[i][14]
}
results.push(row);
}
callBack(results);
if (response.data.length==0) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Salary Info</h1>
<p>Enter first or last name: <input type="text" id="key-word" size="20" /></p>
<p><input type="button" id="start" value="Submit Query for name and Salary" /></p>
<p><input type="button" id="start2" value="Submit Query for Names and Departments" </p>
<h2>First Matching Employing + Salary</h2>
<div id="result">
First result appears here
</div>
<h2>List of All Matching Names</h2>
<div id="names">
All Matching Names Appear Here
</div>
<h2>List of All Matching Names + Departments</h2>
<div id="namesDepartment">
All Matching Names + Departments Appear Here
</div>
My code works fine for the first time but the second time, my object functions returns undefined.
_MANAGE = new Object()
//----------------------------- BG ------------------------------//
var saveBg = {
name : "bg",
url : "AN URL",
data : {
ID :function($this){ return $this.parents("tr").data("id") },
name :function($this){ return $this.parents("tr").find(".name").val() }
}
}
//----------------------------------------------------------------------//
//------------------------- SAVE FUNCTION ------------------------------//
var saveButton = [saveBg];
$(".buttonSave").on("click", function(){
console.log(saveBg);
var buttonName = $(this).data("name");
_MANAGE.saveButton(saveButton, buttonName, $(this));
})
//----------------------------------------------------------------------//
//------------------------- SAVE BUTTON ------------------------------//
_MANAGE.saveButton = function(saveButton, buttonName, $this_button){
for(var i = 0; i < saveButton.length; i++){
if(buttonName == saveButton[i]["name"]){
for(var param in saveButton[i]["data"]){
if(typeof(saveButton[i]["data"][param]) == "function"){
saveButton[i]["data"][param] = saveButton[i]["data"][param]($this_button);
} else {
saveButton[i]["data"][param] = $(saveButton[i]["data"][param]).val();
}
}
if(!saveButton[i]["success"]){
saveButton[i]["success"] = function() {
$this_button.children()
.hide()
.replaceWith("<span style='font-size:0.7em;''>Saved</span>").fadeIn("slow");
setInterval(function(){
$this_button.children().hide().replaceWith('<span class="icon-floppy"> </span>').fadeIn("slow");
}, 1500);
}
}
_MANAGE.ajaxButton(saveButton[i]);
}
}
}
//----------------------------------------------------------------------//
//------------------------- ASYNC FUNCTION ------------------------------//
_MANAGE.ajaxButton = function(ajaxButton) {
var stringData = "";
if(ajaxButton.data){
var loop = 0;
for(var param in ajaxButton["data"]){
if(loop == 0){
stringData += param + "=" + ajaxButton["data"][param];
} else {
stringData += "&" + param + "=" + ajaxButton["data"][param];
}
loop++;
}
}
if(ajaxButton.url && ajaxButton.success && stringData != "") {
$.ajax({
url : ajaxButton.url,
data : stringData,
dataType : "text",
success : ajaxButton.success
});
}
}
<!--THE TABLE -->
<tr data-id="4">
<td><b>4</b></td>
<td><input class="name" type="text" value="A VALUE"></td>
<td>
<!-- THE BUTTON -->
<div class="buttonSave" data-name="bg">
<span class="icon-floppy"></span>
</div>
</td>
</tr>
i found this javascript that allow you to chose an option and once you click the go button. It will redirect you to another site. I have try modify this so i can use it with a button instead of a radio but it doesn't seem to work. Can any 1 help me out ??
Thank you very much.
here the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script language="JavaScript" type="text/javascript">
//chose which page to go to
function Link() {
if (document.fred.r1[0].checked) {
window.top.location = 'http://kshowonline.com/list';
}
if (document.fred.r1[1].checked) {
window.top.location = 'https://www.google.com/';
}
if (document.fred.r1[2].checked) {
window.top.location = 'https://www.yahoo.com/';
}
if (document.fred.r1[3].checked) {
window.top.location = 'https://nodejs.org/';
}
}
//-->
</script>
</head>
<body onload="f19_GetFormCookie();Link();">
<form title="f19_Include" name="fred">
<INPUT type="radio" name="r1">Baseball
<INPUT type="radio" name="r1">Basketball
<INPUT type="radio" name="r1">Soccer
<INPUT type="radio" name="r1">Fencing
<INPUT type="button" value="GO" onclick="f19_SetFormCookie();Link();">
</form>
<script language="JavaScript" type="text/javascript">
<!--
// A Cookie Script to Store and Retrieve
// the values and states of common form elements
// TEXT BOXES - value
// TEXT AREA - value
// CHECK BOX - checked state
// RADIO BUTTON - checked state
// SELECT LIST - selected Index
// Application Notes and Customising Variables
// Application Notes
// Values and states of each element are stored
// as the page is unloaded or form submitted.
// The storage duration is specified by a customising variable
// Stored values and states of elements included in the cookie
// are re-established as the page is reloaded.
// The number and type of elements included must respect
// the maximum cookie size of 4K.
// The Retrieval is initialised by a <BODY> onload event
// The Storage occurs on a <BODY> onunload event
// e.g.
// <body onload="f19_GetFormCookie();" onunload="f19_SetFormCookie();" >
// To include a form element in the Store and Retrieve
// it must be child nodes of an element with a title of 'f19_Include'
// e.g.
// <span title="f19_Include" >
// <INPUT type="text" size="10" >
// <INPUT type="checkbox >
// </span>
// There may be any number of elements titled 'f19_Include' on a page
// and as many child elements of each 'f19_Include' as required.
// All variable, function etc. names are prefixed with 'f19_'
// to minimise conflicts with other JavaScripts
// Customising Variables
var f19_Days = 1; // The cookie will be available on revisits for a specified number of days
var f19_Cookie = 'My Form2'; // The Cookie name
//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--
// Form Compendium f19_Part2 (12-05-2005)
// Functional Code
// No Need To Change ***************************
var f19_TBAry = new Array();
var f19_RCAry = new Array();
var f19_TAAry = new Array();
var f19_SLAry = new Array();
var f19_TBString, f19_RCString, f19_TAString, f19_SLString;
var f19_, f19_exp, f19_st, f19_len, f19_end, f19_st;
var f19_Exp = new Date(new Date().getTime() + f19_Days * 86400000).toGMTString();
function f19_GetFormCookie() {
f19_TBString = f19_GetCookie(f19_Cookie + 'TB');
f19_RCString = f19_GetCookie(f19_Cookie + 'RC');
f19_SLString = f19_GetCookie(f19_Cookie + 'SL');
f19_TAString = f19_GetCookie(f19_Cookie + 'TA');
f19_ = document.getElementsByTagName('*');
for (f19_0 = 0; f19_0 < f19_.length; f19_0++) {
if (f19_[f19_0].title == 'f19_Include') {
f19_Inc = f19_[f19_0].getElementsByTagName('*');
for (f19_1 = 0; f19_1 < f19_Inc.length; f19_1++) {
if (f19_Inc[f19_1].tagName == 'INPUT') {
if (f19_Inc[f19_1].type == 'text') {
f19_TBAry[f19_TBAry.length] = f19_Inc[f19_1];
}
if (f19_Inc[f19_1].type == 'radio' || f19_Inc[f19_1].type == 'checkbox') {
f19_RCAry[f19_RCAry.length] = f19_Inc[f19_1];
}
}
if (f19_Inc[f19_1].tagName == 'TEXTAREA') {
f19_TAAry[f19_TAAry.length] = f19_Inc[f19_1];
}
if (f19_Inc[f19_1].tagName == 'SELECT') {
f19_SLAry[f19_SLAry.length] = f19_Inc[f19_1];
}
}
}
}
if (f19_TBString) {
for (f19_1 = 0; f19_1 < f19_TBAry.length; f19_1++) {
f19_TBAry[f19_1].value = f19_TBString.split('~^~')[f19_1];
}
}
if (f19_RCString) {
for (f19_2 = 0; f19_2 < f19_RCAry.length; f19_2++) {
f19_RCAry[f19_2].checked = false;
if (f19_RCString.split('~^~')[f19_2] == 'true') {
f19_RCAry[f19_2].checked = true;
}
}
}
if (f19_TAString) {
for (f19_3 = 0; f19_3 < f19_TAAry.length; f19_3++) {
f19_TAAry[f19_3].value = f19_TAString.split('~^~')[f19_3];
}
}
if (f19_SLString) {
for (f19_4 = 0; f19_4 < f19_SLAry.length; f19_4++) {
f19_SLAry[f19_4].selectedIndex = f19_SLString.split('~^~')[f19_4];
}
}
}
function f19_GetCookie(name) {
var f19_st = document.cookie.indexOf(name + "=");
var f19_len = f19_st + name.length + 1;
if ((!f19_st) && (name != document.cookie.substring(0, name.length))) return null;
if (f19_st == -1) return null;
var f19_end = document.cookie.indexOf(";", f19_len);
if (f19_end == -1) f19_end = document.cookie.length;
return decodeURI(document.cookie.substring(f19_len, f19_end));
}
function f19_SetFormCookie(value) {
f19_TBString = '';
for (f19_0 = 0; f19_0 < f19_TBAry.length; f19_0++) {
f19_TBString += f19_TBAry[f19_0].value + '~^~';
}
document.cookie = f19_Cookie + "TB=" + encodeURI(f19_TBString) + ";expires=" + f19_Exp + ";path=/;"
f19_RCString = '';
for (f19_1 = 0; f19_1 < f19_RCAry.length; f19_1++) {
f19_RCString += f19_RCAry[f19_1].checked + '~^~';
}
document.cookie = f19_Cookie + "RC=" + encodeURI(f19_RCString) + ";expires=" + f19_Exp + ";path=/;"
f19_TAString = '';
for (f19_0 = 0; f19_0 < f19_TAAry.length; f19_0++) {
f19_TAString += f19_TAAry[f19_0].value + '~^~';
}
document.cookie = f19_Cookie + "TA=" + encodeURI(f19_TAString) + ";expires=" + f19_Exp + ";path=/;"
f19_SLString = '';
for (f19_1 = 0; f19_1 < f19_SLAry.length; f19_1++) {
f19_SLString += f19_SLAry[f19_1].selectedIndex + '~^~';
}
document.cookie = f19_Cookie + "SL=" + encodeURI(f19_SLString) + ";expires=" + f19_Exp + ";path=/;"
}
//-->
</script>
</body>
</html>
You can use onclick event on radio buttons:
http://www.dyn-web.com/tutorials/forms/radio/onclick-onchange.php
You could modify your code to use Buttons instead RadioButtons.
It should resemble the following:
<button name="b1" onclick="f19_SetFormCookie('Baseball')">Baseball</button>
<button name="b2" onclick="f19_SetFormCookie('Basketball')">Basketball</button>
<button name="b3" onclick="f19_SetFormCookie('Soccer')">Soccer</button>
<button name="b4" onclick="f19_SetFormCookie('Fencing')">Fencing</button>
Then you'll have to modify SetFormCookie function to accept the argument - based on which cookie will be set.
when i have to open this page i want to display all contacts in phone with out click on any button.
Here myFunction() displays all contacts.
I have to call `myFunction()`, in this code. I dont know where to call this function. Help me
var ar1 = new Array;
var ar2 = new Array;
var name, number;
var counter = 1;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
filter = [ "displayName", "phoneNumbers" ];
navigator.contacts.find(filter, onSuccess, onError, options);
}
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
name = contacts[i].displayName;
number = contacts[i].phoneNumbers[j].value;
ar1.push(name);
ar2.push(number);
// here i called myFunction(), but it's displaying one contact in multiple times
}
// here i called myFunction(), but it's displaying one contact in multiple times
}
// Here i called myFunction(), the function is not calling
}
function onError(contactError) {
alert('onError!');
}
// where to call this function
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
</script>
</head>
<body>
</br>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<input type="checkbox" id="checkall" value="check" />selectAll</br> <br />
<br /> <br />
</div>
</div>
</body>
</html>
I cannot catch what you want exactly.
if you want to generating phonenumber checkbox list when your app starts,
just call myFunction() in end of onSuccess() callback.
if you want another time, you should define a event handler that you want like below.
$("#PhonenumberListButton" ).click( function() { myFunction(); } );
and your code can occur index exception during loop.
Let's think about below.
each contact has 1 name but has 1 or more phone numbers
your code pushes each name into ar1 and also pushes each phone numbers of contact into ar2
so ar2.length can be greater than ar1.length
your generating display code use ar2.length for loop. it should make exception if any contact has 2 or more phonenumbers.
This's a reason of stop your loop in onSuccess().
Fixed Code
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
name = contacts[i].displayName;
ar1.push(name);
ar2[i] = []; // array for multiple phone#.
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
number = contacts[i].phoneNumbers[j].value;
ar2[i].push(number);
}
}
myFunction(); // display phone numbers
}
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
if ( ar2[i].length ) { // avoid none phone# exception
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i][0] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
}