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>
Related
I want to take out the date validation(a validation to my code to validate year between 1930 and the current year and if it's not correct it should print an error) to another separate new function, Instead of the Addmovie function.
i want to make another new function called datevalidation and I want to add date validation, which is currently in the addmovie function.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Week 07 Pass Submission</title>
<script src="./w7p.js"></script>
</head>
<body>
<header>
<h1>Week 07 Pass Submission</h1>
</header>
<article>
<form>
<label for="movie">Movie title</label>
<input type="text" id="movie" /><br /><br />
<span id="yearValidation" style="color: red"></span>
<br />
<label for="year">Release year</label>
<input type="text" id="year" /><br /><br />
<input type="button" id="add" value="Add">
<input type="button" id="show" value="List All">
</form><br />
<div style="padding-left: 20px;" id="list"></div>
</article>
</body>
</html>
JavaScript Code
var movieTitle = [];
var movieReleaseYear = [];
function init() {
var add = document.getElementById('add');
add.onclick = () => addMovie(2022);
var show = document.getElementById('show');
show.onclick = () => displayData();
}
function addMovie(currentYear) {
var name = document.getElementById('movie');
var year = document.getElementById('year');
var year = document.getElementById('year').value;
if (year <= 1930 || year >= currentYear) {
document.getElementById('yearValidation').innerHTML = 'Error';
} else {
document.getElementById('yearValidation').innerHTML = '';
}
movieTitle.push(name.value);
movieReleaseYear.push(year.value);
}
function displayData() {
if (movieTitle.length == 0) {
document.getElementById('list').innerHTML = 'there is no data';
} else {
var output = '';
movieTitle.forEach(
(element, index) =>
(output +=
' ' +
(index + 1) +
'. ' +
element +
'\t\t' +
movieReleaseYear[index] +
'<br />')
);
document.getElementById('list').innerHTML = output;
}
}
window.onload = init;
You can declare a separate function dateValidation() and call it inside addMovie()
var movieTitle = [];
var movieReleaseYear = [];
function init() {
var add = document.getElementById('add');
add.onclick = () => addMovie(2022);
var show = document.getElementById('show');
show.onclick = () => displayData();
}
function dateValidation(year,currentYear){
if (year <= 1930 || year >= currentYear) {
document.getElementById('yearValidation').innerHTML = 'Error';
}
movieTitle.push(name.value);
movieReleaseYear.push(year.value);
}
function addMovie(currentYear) {
var name = document.getElementById('movie');
var year = document.getElementById('year').value;
dateValidation(year,currentYear);
}
function displayData() {
if (movieTitle.length == 0) {
document.getElementById('list').innerHTML = 'there is no data';
} else {
var output = '';
movieTitle.forEach(
(element, index) =>
(output +=
' ' +
(index + 1) +
'. ' +
element +
'\t\t' +
movieReleaseYear[index] +
'<br />')
);
document.getElementById('list').innerHTML = output;
}
}
window.onload = init;
I have a program that is suppose to ask the user for their ID, First Name, Last Name, select a Rank (grade level), and the GPA. After all fields go through error checking, the data should then be put into an object called student. Next the student object should be pushed to the Summary Array. Displaying the first and last name, next line ID, next line Class Rank, next line GPA.
UPDATE CURRENTLY: all error checking (if/elses) works! Secondly, only the "--------" happens when Add Student is pressed besides the error checking.
Full Code:
var studentList = []
var studentID;
var studentFirst;
var studentLast;
var Rank;
var studentGPA;
var Summary = [];
studentID = document.querySelector("#Text1");
studentFirst = document.querySelector("#Text2");
studentLast = document.querySelector("#Text3");
Rank = document.querySelector("#Select1");
studentGPA = document.querySelector("#Text4");
function AddListeners() {
studentID.addEventListener("mouseenter", ChangeColor1);
studentID.addEventListener("mouseleave", ChangeColorBack1);
studentFirst.addEventListener("mouseenter", ChangeColor2);
studentFirst.addEventListener("mouseleave", ChangeColorBack2);
studentLast.addEventListener("mouseenter", ChangeColor3);
studentLast.addEventListener("mouseleave", ChangeColorBack3);
Rank.addEventListener("mouseenter", ChangeColor4);
Rank.addEventListener("mouseleave", ChangeColorBack4);
studentGPA.addEventListener("mouseenter", ChangeColor5);
studentGPA.addEventListener("mouseleave", ChangeColorBack5);
studentGPA.addEventListener("keypress", ShowKey);
}
function ChangeColor1() {
studentID.style.backgroundColor = "yellow";
}
function ChangeColorBack1() {
studentID.style.backgroundColor = "";
}
function ChangeColor2() {
studentFirst.style.backgroundColor = "yellow";
}
function ChangeColorBack2() {
studentFirst.style.backgroundColor = "";
}
function ChangeColor3() {
studentLast.style.backgroundColor = "yellow";
}
function ChangeColorBack3() {
studentLast.style.backgroundColor = "";
}
function ChangeColor4() {
Rank.style.backgroundColor = "yellow";
}
function ChangeColorBack4() {
Rank.style.backgroundColor = "";
}
function ChangeColor5() {
studentGPA.style.backgroundColor = "yellow";
}
function ChangeColorBack5() {
studentGPA.style.backgroundColor = "";
}
function ShowKey(e) {
if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 46) {
e.preventDefault();
}
}
function Create() {
studentID = document.getElementById('Text1').value;
studentFirst = document.getElementById('Text2').value;
studentLast = document.getElementById('Text3').value;
Rank = document.getElementById('Select1').value;
studentGPA = document.getElementById('Text4').value;
if (!studentList.includes(studentID)) {
if (studentID != '') {
if (studentFirst != '') {
if (studentLast != '') {
if (Rank != -1) {
if (studentGPA != '') {
if (studentGPA > 0 && studentGPA < 4) {
var Student = {
studentID: document.getElementById('Text1').value,
studentFirst: document.getElementById('Text2').value,
studentLast: document.getElementById('Text3').value,
Rank: document.getElementById('Select1').value,
studentGPA: document.getElementById('Text4').value,
};
Summary.push(Student);
document.getElementById("studentinfo").innerHTML = "";
for (var i = 0; i < Summary.length; i++) {
document.getElementById("studentinfo").innerHTML +=
"------------------------------------------------------" + "<br/>"
"Name: " + Summary[i].studentFirst + " " + Summary[i].studentLast + "<br/>" +
"ID: " + Summary[i].studentID + "<br/>" +
"Class: " + Summary[i].Rank + "<br/>" +
"GPA: " + Summary[i].studentGPA + "<br/>";
}
} else
alert("GPA must be between 0 and 4");
} else
alert("GPA is blank");
} else
alert("Rank has not been selected");
} else
alert("Last Name is blank");
} else
alert("First Name is blank");
} else
alert("Student ID is blank");
} else
alert("Duplicate Student ID");
}
<body onload="AddListeners()">
ID:<input id="Text1" type="text" />
<br> First Name:<input id="Text2" type="text" />
<br> Last Name:<input id="Text3" type="text" />
<br>
<select id="Select1">
<option value="-1">(Select a Rank)</option>
<option>Freshmen</option>
<option>Sophomore</option>
<option>Junior</option>
<option>Senior</option>
</select>
<br> GPA:
<input id="Text4" type="text" />
<br>
<input id="Button1" type="button" value="Add Student" onclick="Create()" />
<br> All added students today:
<br>
<div id="studentinfo"></div>
<br>
</body>
You need to initialize Summary to an empty array. Otherwise, Summary.push() gets an error because you can't push onto undefined.
The index of the prompt option in the Rank menu is 0, not 1, so you should check for that in the validation.
The Create() function reassigns all the variables that contain the input elements, replacing them with their values. You should use different variables, or just use the .value properties of the global variables.
You need to convert the value of Rank to a number before comparing with numbers.
You're missing a + at the end of the first line of the string you're appending to the DIV, so you're only adding the ---- line.
When checking for duplicates, you need to compare studentID.value with the studentID property of the array element, not the whole array element. And you should be searching Summary, not studentList.
var studentList = []
var studentID;
var studentFirst;
var studentLast;
var Rank;
var studentGPA;
var Summary = [];
studentID = document.querySelector("#Text1");
studentFirst = document.querySelector("#Text2");
studentLast = document.querySelector("#Text3");
Rank = document.querySelector("#Select1");
studentGPA = document.querySelector("#Text4");
function AddListeners() {
studentID.addEventListener("mouseenter", ChangeColor1);
studentID.addEventListener("mouseleave", ChangeColorBack1);
studentFirst.addEventListener("mouseenter", ChangeColor2);
studentFirst.addEventListener("mouseleave", ChangeColorBack2);
studentLast.addEventListener("mouseenter", ChangeColor3);
studentLast.addEventListener("mouseleave", ChangeColorBack3);
Rank.addEventListener("mouseenter", ChangeColor4);
Rank.addEventListener("mouseleave", ChangeColorBack4);
studentGPA.addEventListener("mouseenter", ChangeColor5);
studentGPA.addEventListener("mouseleave", ChangeColorBack5);
studentGPA.addEventListener("keypress", ShowKey);
}
function ChangeColor1() {
studentID.style.backgroundColor = "yellow";
}
function ChangeColorBack1() {
studentID.style.backgroundColor = "";
}
function ChangeColor2() {
studentFirst.style.backgroundColor = "yellow";
}
function ChangeColorBack2() {
studentFirst.style.backgroundColor = "";
}
function ChangeColor3() {
studentLast.style.backgroundColor = "yellow";
}
function ChangeColorBack3() {
studentLast.style.backgroundColor = "";
}
function ChangeColor4() {
Rank.style.backgroundColor = "yellow";
}
function ChangeColorBack4() {
Rank.style.backgroundColor = "";
}
function ChangeColor5() {
studentGPA.style.backgroundColor = "yellow";
}
function ChangeColorBack5() {
studentGPA.style.backgroundColor = "";
}
function ShowKey(e) {
if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 46) {
e.preventDefault();
}
}
function Create() {
if (!Summary.find(s => s.studentID == studentID.value)) {
if (studentID.value != '') {
if (studentFirst.value != '') {
if (studentLast.value != '') {
if (Rank.selectedIndex != 0) {
if (studentGPA.value != '') {
let GPAVal = parseFloat(studentGPA.value);
if (GPAVal > 0 && GPAVal < 4) {
var Student = {
studentID: studentID.value,
studentFirst: studentFirst.value,
studentLast: studentLast.value,
Rank: Rank.value,
studentGPA: studentGPA.value,
};
Summary.push(Student);
document.getElementById("studentinfo").innerHTML = "";
for (var i = 0; i < Summary.length; i++) {
document.getElementById("studentinfo").innerHTML +=
"------------------------------------------------------" + "<br/>" +
"Name: " + Summary[i].studentFirst + " " + Summary[i].studentLast + "<br/>" +
"ID: " + Summary[i].studentID + "<br/>" +
"Class: " + Summary[i].Rank + "<br/>" +
"GPA: " + Summary[i].studentGPA + "<br/>";
}
} else
alert("GPA must be between 0 and 4");
} else
alert("GPA is blank");
} else
alert("Rank has not been selected");
} else
alert("Last Name is blank");
} else
alert("First Name is blank");
} else
alert("Student ID is blank");
} else
alert("Duplicate Student ID");
}
<body onload="AddListeners()">
ID:<input id="Text1" type="text" />
<br> First Name:<input id="Text2" type="text" />
<br> Last Name:<input id="Text3" type="text" />
<br>
<select id="Select1">
<option>(Select a Rank)</option>
<option>Freshmen</option>
<option>Sophomore</option>
<option>Junior</option>
<option>Senior</option>
</select>
<br> GPA:
<input id="Text4" type="text" />
<br>
<input id="Button1" type="button" value="Add Student" onclick="Create()" />
<br> All added students today:
<br>
<div id="studentinfo"></div>
<br>
</body>
Rank has no selectedIndex because Rank is not an element or node.
Rank = document.getElementById('Select1').value;
You should set the value attribute on your option tags.
<option value="-1">(Select a Rank)</option>
if (Rank != -1) {
How to check value in input using getElementsByClassName , Like this ?
When i load page, I want to alert
HAVE VALUE 3 INPUT
NOT HAVE VALUE 2 INPUT
How can i do that ?
................................................................................................................................................
http://jsfiddle.net/3AaAx/37/
<input type="text" class="xxx" value="111"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="222"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="333"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
// this function for use getElementsByClassName on IE 7 and 8 //
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', #class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
var xxx_var = document.getElementsByClassName('xxx');
alert(xxx_var.length);
});
</script>
Add below code after var xxx_var = document.getElementsByClassName('xxx');
var inputCount=0,nonInputCount=0;
for(var i=0;i<xxx_var.length;i++){
if(xxx_var[i].value != ""){
inputCount++;
}else{
nonInputCount++;
}
}
alert("Input Count " + inputCount + " , and non input count " +nonInputCount );
If you use jquery it will be very easier code.
Let me know if you didn't understand.
Thanks
Raviranjan
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).
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");
}
}
}