Im making a contacts book, and with each new entry it generates a Div with all the information inside. I have gotten as far as giving each generated div a unique ID, and each button generated with the Div a unique ID, however I am having trouble associating the buttons with the div and allowing it to perform functions (such as toggling the visibility of the div).
Any help you can give is greatly appreciated, as I will soon be bald from frustration.
Updated Code with suggestions
The code that generates the DIV and Button:
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
myControls.push(control);
var childDiv =
"<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
"<div id='" + divid + "' " + "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
"<br>" + "Surname: " + this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
"Date Of Birth: " + this.days + "/" + this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
"<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
"<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" + "</div>" + "</div>"
return childDiv ;
}
The entire code
var surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ; //Declaring variables for the fields
var Contact = function(surname,firstName,date, phone , address , post, email, group){
this.surname = surname ;
this.firstName = firstName ;
this.birthdayDate = new Date (date) ;
this.phone = phone;
this.address= address;
this.email = email;
this.post = post;
this.group = group;
this.selected = false ;
}
var contacts = [];
divid = 0;
buttonid = 1000;
myControls = [];
var getDate = function() {
for (var i= 0, j=contacts.length;i<j;i++){
var y = contacts[i].birthdayDate.getFullYear();
var m = contacts[i].birthdayDate.getMonth();
var d = contacts[i].birthdayDate.getDate();
contacts[i].days = d;
contacts[i].months = m + 1;
contacts[i].years = y ;
var today = new Date() ;
var ty = today.getFullYear();
contacts[i].bdThisYear = new Date(ty,m,d, 0 , 0 , 0);
}
}
var daysUntilBirthday = function(){
for (var i= 0, j=contacts.length;i<j;i++){
var today = new Date() ;
contacts[i].daysUntil = Math.round((contacts[i].bdThisYear - today ) /1000/60/60/24+1);
if (contacts[i].daysUntil <= 0){
contacts[i].daysUntil = contacts[i].daysUntil + 365 ;
}
}
}
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
myControls.push(control);
var childDiv =
"<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
"<div id='" + divid + "' " + "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
"<br>" + "Surname: " + this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
"Date Of Birth: " + this.days + "/" + this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
"<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
"<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" + "</div>" + "</div>"
return childDiv ;
}
var addContact = function(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ){
if(surnameField.value){
a = new Contact(surnameField.value, firstNameField.value,birthdayField.value, phoneField.value, addressField.value, postField.value, emailField.value, groupField.value);
contacts.push(a);
}else{ alert("Please complete all fields")}
}
var clearUI = function(){
var white = "#fff";
surnameField.value = "";
surnameField.style.backgroundColor = white;
firstNameField.value = "";
firstNameField.style.backgroundColor = white;
birthdayField.value="";
birthdayField.style.backgroundColor = white;
phoneField.value = "";
phoneField.style.backgroundcolor = white;
addressField.value = "";
addressField.style.backgroundcolor = white;
postField.value = "";
postField.style.backgroundcolor = white;
emailField.value = "";
emailField.style.backgroundcolor = white;
groupField.value="";
groupField.style.backgroundcolor = white;
}
var updateList = function(){
divid = 0;
buttonid = 1000;
myControls = []
var tableDiv = document.getElementById("parentDiv"),
cDiv = "<BR>" + "<div align='center'> Click a contact to expand</div>" ;
for (var i= 0, j=contacts.length;i<j;i++){
var cntct = contacts[i];
cDiv += cntct.generateDiv();
}
tableDiv.innerHTML = cDiv;
getDate();
daysUntilBirthday();
saveContacts();
}
var add = function(){
;
addContact(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField);
clearUI();
daysUntilBirthday();
getDate();
updateList();
};
var saveContacts = function(){
var cntcts = JSON.stringify(contacts);
if (cntcts !==""){
localStorage.contacts = cntcts;
}else{
alert("Could not save contacts");
}
}
var loadContacts = function(){
var cntcts = "";
if(localStorage.contacts !== undefined){
cntcts = localStorage.contacts;
contacts = JSON.parse(cntcts);
var proto = new Contact();
for (var i=0; i<contacts.length; i++){
var cntct = contacts[i]
cntct.__proto__ = proto;
cntct.birthdayDate = new Date(cntct.birthdayDate);
}
}
}
var clearContacts = function(){
contacts = [];
updateList();
}
//var periodUpdate = function(){
// setInterval(updateList, 10000);
//}
window.onload = function(){
loadContacts();
updateList();
surnameField = document.getElementById("surname");
firstNameField = document.getElementById("firstName")
birthdayField = document.getElementById("birthday");
phoneField = document.getElementById("phone");
addressField = document.getElementById("address");
postField = document.getElementById("post");
emailField = document.getElementById("email");
groupField = document.getElementById("group");
addButton = document.getElementById("addButton");
addButton.onclick = add;
delButton = document.getElementById("delButton");
delButton.onclick = clearContacts;
clearUI();
// periodUpdate();
}
The HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="contacts.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-1.8.3.min.js">
$(document).ready(function(){
(".btnForDiv").on("click", function(){
// get the ID of the button
var id = $(this).prop("id");
var divid;
// now find the div Id related to this button
for (var i = 0, len = myControls.length; i < len; i++){
if (myControls[i][1] == id){
divid = myControls[i][0];
break;
}
}
// you now have the div,so toggle it.
$("#" + divid).toggle();
});
});
</script>
<div><title>Contacts Book</title></div>
</head>
<body>
<div class="information">
<heading><h1>Contacts Book</h1></heading>
</div>
<p><div class="information">Enter the contacts details below and click Add or select to view an existing contact.</div></p>
<hr>
<div class="entrydiv">
<table class="entryforms">
<br>
<tr>
<td>Surname</td><td><input type="text" class="inputboxes" id="surname" /></td>
</tr>
<tr>
<td>First Name</td><td><input type="text" class="inputboxes" id="firstName" /></td>
</tr>
<tr>
<td>Birthday</td><td><input type="date" class="inputboxes" id="birthday" /></td>
</tr>
<tr>
<td>Phone Number</td><td><input type="text" class="inputboxes" id="phone"></textarea></td>
</tr>
<tr>
<td>Email Address</td><td><input type="text" class="inputboxes" id="email" /></td>
</tr>
<tr>
<td>Address</td><td><input type="text" class="inputboxes" id="address"/></td>
</tr>
<tr>
<td>Postcode</td><td><input type="text" class="inputboxes" id="post" /></td>
</tr>
<tr>
<td>Group</td><td><select class="inputboxes" id="group"/>
<option value="Business">Business</option>
<option value="Educational">Educational</option>
<option value="Friend">Friend</option>
</td>
</tr>
</table>
<br>
<button id="addButton">Add Contact</button>
<button id="delButton">Delete Contacts</button>
</div>
<hr>
<div class="tablediv">
<h2 class="information" align="center">Contacts</h2>
<div id="parentDiv"></div>
</div>
</body>
</html>
The Solution
First of all massive thanks to Darren for his advice, which turns out to be spot on (with minor change)
First error I made was inserting jquery, I had
<script src="jquery-1.8.3.min.js">
//code
</script>
When I needed
<script src="jquery-1.8.3.min.js"></script>
<script>
//code
</script>
So that very minor mistake held me back for a while.
Secondly I used:
$(document).on('click','.btnForDiv',function(){
To call the Onclick event for my btnForDiv class buttons and the rest was all Darren :)
Thanks again
You could do a few things here.
One idea would be to store your generated div and button ID's in an array. You can then search this array for a given button ID to find its corresponding div.
For example (not tested...)
// outside your generatedDiv method
var myControls = new Array();
// then inside your generatedDiv method
var control = new Array();
control[0] = divId;
control[1] = buttonId;
myControls.push(control);
When you click your button you can grab its ID then search through the myControls array and look for the corresponding div
you could do a single function in jQuery to handle all the click for all of your generated buttons.
again (not tested) - give all your buttons a class, for example btnForDiv
$(document).ready(function(){
$(".btnForDiv").click(function(){
// get the ID of the button
var id = $(this).prop("id");
var divId;
// now find the div Id related to this button
for (var i = 0, len = myControls.length; i < len; i++){
if (myControls[i][1] == id){
divId = myControls[i][0];
break;
}
}
// you now have the div,so toggle it.
$("#" + divId).toggle();
});
});
I'm not 100% sure what your question was, though took a stab in the dark to help..
UPDATE
Because your div's are generated and added to the DOM dynamically you may have to use on instead of click - this will bind the click event to dynamic elements.
So try this:
$(".btnForDiv").on("click", function(){
// get the id.... etc...
});
also, make sure you did add the class btnForDiv to your dynamically generated buttons
this.firstName + " " + this.surname + "<button style='color: black;' id='" + buttonid + "b'" + " class='btnForDiv'> Button </button>" +
Related
I'm making a page with a list of products (which are loads using ajax) but i want to show only 6 products/page but i don't know how to do it and i don't find any examples that implements what i want. So for example if i have 20 products i want to show 6 in the first page, 6 in the second, .. etc to the last product in the last page (the page is always the same only the products change).
So in the end of the page i must have page 1-n
Can someone help me?
this is the js that load the products and show them one below the other:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "json/projects.json",
dataType: "json",
success: function (data) {
showInfo(data);
},
});
});
function showInfo(data) {
var htmlString = "";
if (data.length == 0) {
htmlString =
"<span id = " +
"message>" +
"Non è stato trovato alcun progetto" +
"</span>";
$("#list").append(htmlString);
} else {
//altrimenti stampo data
for (i = 0; i < data.length; i++) {
//scorro tutto il mio file json
htmlString =
"<div class = " + "project id = " + data[i].id + ">" +
"<div class =" + "row-list>" +
"<div class = " + "title>" + data[i].title + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/user.png>" + data[i].username + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/budget.png>" + data[i].budget + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/data.png>" + data[i].data + "</div>" +
"<div class = " + "flag>" + data[i].flag + "</div>" +
"</div>";
// collego al div #list le informazioni
$("#list").append(htmlString);
}
// aggiungo l'handler per visualizzare i dettagli quando un progetto viene cliccato
$(".project").click(function () {
window.location.href = "details.php?id=" + $(this).attr("id");
});
}
}
If the page doesn't change, you can stay on the same page while simply changing the products shown.
Here's a simplified version to demonstrate how this could work:
// create 20 product names
let products = [];
for (let i=1; i<=20; i++) {
products.push(`This is Product Name ${i}`);
}
let firstShown = 0;
const display = document.getElementById('display');
// display up to 6 products on page
function addToDisplay(first) {
display.innerHTML = '';
let last = Math.min(first+5, products.length-1);
for (let i = first; i <= last; i++) {
let li = document.createElement('li');
li.innerHTML = products[i];
display.appendChild(li);
}
}
function forward () {
display.innerHTML = '';
firstShown += 5;
addToDisplay(firstShown);
}
function back () {
display.innerHTML = '';
firstShown = Math.max(firstShown-5, 0);
addToDisplay(firstShown);
}
// show initial 6 producs
addToDisplay(firstShown);
<p>Display multiple products 6 at a time<br/>
<button type="button" onclick="back();">Back</button>
<button type="button" onclick="forward();">Forward</button>
</p>
<ul id="display"></ul>
I am trying to achieve a dropdown box in my webpage which lists the options from the values in the database. I have achieved showing the listed options for the dropdown, but when I select the option it is not set to a value. In other words I have a doubt whether my dropdown is initialized or not.
I have added the required snippet for the action.
function add_row() {
table = document.getElementById('b_book');
var rowData = document.createElement('tr');
rowData.innerHTML = '<td>' + slno +
'</td><td id="dbSNO"><select id="SNO[' + slno + ']" onchange="detail_fetcher(this.value)" onselect="detail_fetcher(this.value)" onload="detail_fetcher(this.value)"></select></td>' +
'<td id="dbLNO"><input type="text" id="LNO[' + slno + ']" list="lot_srch_list" onkeydown="LNO_COL(event,this.value,this.id)" onfocus="lotNo_select()"/></td>' +
'<td><input type="text" id="dbMTR[' + slno + ']"/></td><td id="dbWT[' + slno + ']"></td><td id="dbMWT[' + slno + ']"></td><td id="GPM[' + slno + ']"></td><td id="dbTONE[' + slno + ']"></td><td><button id="btn_rem[' + slno + ']" onclick="remove_row()">Remove</button></td>';
table.appendChild(rowData);
slno += 1;
}
function LNO_COL(e, lno, hashtag) {
var beg_pos = hashtag.indexOf('[') + 1;
var end_pos = hashtag.indexOf(']');
var hash_pos = hashtag.substring(hashtag.lastIndexOf('[') + 1, hashtag.lastIndexOf(']'));
var postIN = 'par=' + parname.value + '&lno=' + lno;
if (e.ctrlKey) {
sNo_list = document.getElementById('SNO[' + hash_pos + ']');
sNo_list.innerHTML = '';
var XMLhLNO = new XMLHttpRequest();
XMLhLNO.onreadystatechange = function () {
if ((this.readyState === 4) && (this.status === 200)) {
var result = this.responseText;
var JSON_result = JSON.parse(result);
for (z in JSON_result) {
var sno_opt;
sno_opt = document.createElement('option');
sno_opt.value = JSON_result[z].slno;
sno_opt.text = JSON_result[z].slno;
sNo_list.appendChild(sno_opt);
}
}
};
XMLhLNO.open('POST', 'sno_lot_par2.php', true);
XMLhLNO.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
XMLhLNO.send(postIN);
detail_fetcher(hashtag);
}
}
function detail_fetcher(hash_position) {
var row_no = hash_position.substring(hash_position.lastIndexOf('[') + 1, hash_position.lastIndexOf(']'));
var serial_row = document.getElementById('SNO[' + row_no + ']');
alert(serial_row.);
/* var XMLfetcher = new XMLHttpRequest();
XMLfetcher.onreadystatechange = function()
{
if((this.readyState == 4)&&(this.status == 200))
{
var src_result = this.responseText;
var JSON_res = JSON.parse(src_result);
alert(serial_row_db);
alert(src_result);
}
};
XMLfetcher.open('POST','srch_lot2.php',true);
XMLfetcher.setRequestHeader('Content-type','application/x-www-form-urlencoded');
XMLfetcher.send(('row=' + serial_row_db));
*/
}
I have tried using value method, selecteditem(index) method but none of them proves to be successful.
Note: I want to use pure JavaScript as I am quite confused with using jQuery.
So I'm working on SP 2013 and have a document library which has three Lookup columns viz : Business Unit, Axis Product and Policy form. What I'm trying to do is I have managed to group by the List items first by Business Unit column and then by the Axis Product Column. This works fine but recently I'm trying to show the count of the number of items inside a particular Axis Product. Which would be like - Axis Product : "Some Value" (Count).
I'm able to show this count with Business Unit, but not able to do this with Axis Product. So I tried querying the library with both Business Unit and Axis Product to get the count for Axis Product, I'm not sure about this approach and currently I'm getting an error message:
'collListItemAxisProduct' is undefined.
Any help would be appreciated as I've been stuck on this for a long time now. Here is my code below :
// JavaScript source code
$(function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', oGroupBy.GetDataFromList);
});
function GroupBy()
{
this.clientContext = "";
this.SiteUrl = "/sites/insurance/products";
this.lookUpLIst = "AxisBusinessUnit";
this.AxisProductlookUpList = "AXIS Product";
this.lookUpItems = [];
this.lookUpColumnName = "Title";
this.AxisProductlookupItems = [];
this.AProducts = [];
this.index = 0;
this.secondindex = 0;
this.parentList = "AXIS Rules Library";
this.html = "<div id='accordion'><table cellspacing='35' width='100%'><tr><td width='8%'>Edit</td><td width='13%'>Name</td><td width='13%'>Modified</td><td width='13%'>Underwriting Comments</td><td width='13%'>Policy Form Applicability</td><td width='13%'>AXIS Product</td><td width='13%'>Business Unit</td></tr>";
}
function MultipleGroupBy()
{
this.AxProducts = [];
this.SecondaryGroupBy = [];
this.count = "";
this.BusinessUnit = "";
this.html = "";
}
function UI()
{
this.id = "";
this.name = "";
this.modified = "";
this.acturialComments = "";
this.underWritingComments = "";
this.policyFormApplicability = [];
this.axisProduct = [];
this.businessUnit = [];
this.itemcheck = "";
this.Count = 0;
this.header = "";
this.AxisProductCount = 0;
this.trID = "";
this.SecondaryID = "";
this.LandingUrl = "&Source=http%3A%2F%2Fecm%2Ddev%2Fsites%2FInsurance%2FProducts%2FAXIS%2520Rules%2520Library%2FForms%2FGroupBy%2Easpx";
}
var oUI = new UI();
var oGroupBy = new GroupBy();
var oMultipleGroupBy = new MultipleGroupBy();
GroupBy.prototype.GetDataFromList = function () {
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.lookUpLIst);
var APList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.AxisProductlookUpList);
var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);
var secondcamlQuery = new SP.CamlQuery();
this.secondListItem = APList.getItems(secondcamlQuery);
oGroupBy.clientContext.load(collListItem);
oGroupBy.clientContext.load(secondListItem);
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.BindDataFromlookUpList), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.BindDataFromlookUpList = function (seneder,args) {
var listenumerator = collListItem.getEnumerator();
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
oGroupBy.lookUpItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
GroupBy.prototype.GetDataFromParent = function(lookUpItems)
{
var oList1 = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Business_x0020_Unit\'/>' +
'<Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq></Where></Query></View>');
this.collListItem1 = oList1.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItem1, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.CreateHTMLGroupBy), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.CreateHTMLGroupBy = function (sender,args)
{
var listenumerator = this.collListItem1.getEnumerator();
var axisproductlistenumarator = secondListItem.getEnumerator();
while (axisproductlistenumarator.moveNext()) {
var currentitem = axisproductlistenumarator.get_current(); oGroupBy.AxisProductlookupItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oUI.Count = this.collListItem1.get_count();
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oUI.trID = oGroupBy.lookUpItems[oGroupBy.index];
oMultipleGroupBy.BusinessUnit = oGroupBy.lookUpItems[oGroupBy.index];
oGroupBy.html = oGroupBy.html + "<table style='cursor:pointer' id='" + oUI.trID.replace(" ", "") + "' onclick='javascript:oUI.Slider(this.id)'><tr><td colspan='7'><h2 style='width:1100px;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>Business Unit : " + oGroupBy.lookUpItems[oGroupBy.index] + " " + "<span> (" + oUI.Count + ")</span></h2></td></tr></table>";
}
oUI.businessUnit.length = 0;
oMultipleGroupBy.SecondaryGroupBy.length = 0;
oMultipleGroupBy.SecondaryGroupBy.push(oUI.trID);
oMultipleGroupBy.html = "";
if (oUI.Count > 0) {
if (listenumerator != undefined) {
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
if (currentitem != undefined) {
oUI.id = currentitem.get_item("ID");
oUI.name = currentitem.get_item("FileLeafRef");
oUI.modified = currentitem.get_item("ModifiedDate");
//oUI.policyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
oUI.underWritingComments = currentitem.get_item("Underwriting_x0020_Comments");
//oUI.axisProduct = currentitem.get_item("AXIS_x0020_Product");
var lookupPolicyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
var lookupField = currentitem.get_item("Business_x0020_Unit");
var lookupAxisProduct = currentitem.get_item("AXIS_x0020_Product");
oUI.businessUnit.length = 0;
for (var i = 0; i < lookupField.length; i++) { oUI.businessUnit.push(lookupField[i].get_lookupValue());
}
oUI.axisProduct.length = 0;
for (var m = 0; m < lookupAxisProduct.length; m++) { oUI.axisProduct.push(lookupAxisProduct[m].get_lookupValue());
}
oUI.policyFormApplicability.length = 0;
for (var a = 0; a < lookupPolicyFormApplicability.length; a++)
{
oUI.policyFormApplicability.push(lookupPolicyFormApplicability[a].get_lookupValue());
}
oGroupBy.CreateUI(oUI);
}
}
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oGroupBy.html = oGroupBy.html + oMultipleGroupBy.html;
}
}
}
oGroupBy.index = oGroupBy.index + 1;
if (oGroupBy.index <= oGroupBy.lookUpItems.length) {
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
if(oGroupBy.index == oGroupBy.lookUpItems.length + 1)
{
oGroupBy.html = oGroupBy.html + "</table></div>";
$("#contentBox").append(oGroupBy.html);
$(".hide,.sd-hide").hide();
}
}
UI.prototype.Slider = function (id) {
$("#MSOZoneCell_WebPartWPQ3").click();
//$(".hide").hide();
var elements = document.querySelectorAll('[data-show="' + id + '"]');
$(elements).slideToggle();
}
UI.prototype.SecondarySlider = function (id) {
var elements = document.querySelectorAll('[data-secondary="' + id + '"]');
$(elements).slideToggle();
}
GroupBy.prototype.CreateUI = function (oUI) {
var BusinessUnit = "";
var AxisProduct = "";
var Policyformapplicability = "";
var tempBUnit = "";
for (var i = 0; i < oUI.businessUnit.length; i++) {
BusinessUnit = BusinessUnit + oUI.businessUnit[i] + ",";
}
for (var m = 0; m < oUI.axisProduct.length; m++) {
AxisProduct = AxisProduct + oUI.axisProduct[m] + ",";
}
for (var a = 0; a < oUI.policyFormApplicability.length; a++) {
Policyformapplicability = Policyformapplicability + oUI.policyFormApplicability[a] + ",";
}
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList1SecondGroupBy = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Business_x0020_Unit\' /><Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq>' +
'<Eq><FieldRef Name=\'AXIS_x0020_Product\' /><Value Type=\'LookupMulti\'>' + oGroupBy.AxisProductlookupItems[oGroupBy.secondindex] + '</Value></Eq></And></Where><OrderBy><FieldRef Name=\'Title\' Ascending=\'True\' /></OrderBy></Query><View>');
this.collListItemAxisProduct = oList1SecondGroupBy.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItemAxisProduct, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
if (collListItemAxisProduct != undefined) {
//oGroupBy.clientContext.load(collListItemAxisProduct);
var AxisProductlistenumerator = this.collListItemAxisProduct.getEnumerator();
if (AxisProductlistenumerator != undefined) {
oUI.AxisProductCount = this.collListItemAxisProduct.get_count();
oGroupBy.AProducts.length = 0;
if (AxisProduct != "") {
oGroupBy.AProducts = AxisProduct.split(',');
}
oGroupBy.AProducts.splice(oGroupBy.AProducts.length - 1, 1);
//alert(oGroupBy.AProducts.length);
var link = "/sites/Insurance/Products/AXIS%20Rules%20Library/Forms/EditForm.aspx?ID=" + oUI.id + oUI.LandingUrl;
var editicon = "/sites/insurance/products/_layouts/15/images/edititem.gif?rev=23";
for (var i = 0; i < oGroupBy.AProducts.length; i++) {
var SecondaryGBTableID = "";
if (oGroupBy.AProducts[i].replace(" ", "") != "") {
SecondaryGBTableID = oGroupBy.AProducts[i].replace(/\s/g, "") + oMultipleGroupBy.BusinessUnit.replace(/\s/g, "");
SecondaryGBTableID = SecondaryGBTableID.replace("&", "");
var isPresent = $.inArray(oGroupBy.AProducts[i].replace(/\s/g, ""), oMultipleGroupBy.SecondaryGroupBy);
}
oUI.SecondaryID = oUI.trID.replace("/\s/g", "") + oGroupBy.AProducts[i].replace("/\s/g", "");
if ((isPresent <= -1)) {
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr style='margin-left:10px;margin-bottom:1px solid grey;' cellspacing='36'><td ><h3 class='hide' onclick='javascript:oUI.SecondarySlider(this.id);' id='" + oUI.SecondaryID + "' data-show='" + oUI.trID.replace(" ", "") + "' style='cursor:pointer;width:100%;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'> - AXIS Product : " + oGroupBy.AProducts[i] + " " + "<span> (" + oUI.AxisProductCount + ")</span></h3></td></tr>";
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr><td><table class='hide' data-show='" + oUI.trID.replace(" ", "") + "' width='100%' cellspacing='36' id='" + SecondaryGBTableID + "'><tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr></table></td></tr>";
}
else {
if ($("#" + SecondaryGBTableID).html() != undefined) {
$("#" + SecondaryGBTableID).append("<tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr>");
oMultipleGroupBy.html = $("#divMultiplegroupBy").html();
}
}
document.getElementById("divMultiplegroupBy").innerHTML = oMultipleGroupBy.html;
if ((isPresent <= -1) && (oGroupBy.AProducts[i] != "")) {
oMultipleGroupBy.SecondaryGroupBy.push(oGroupBy.AProducts[i].replace(/\s/g, ""));
}
}
}
}
else {
oGroupBy.secondindex = oGroupBy.secondindex + 1;
oGroupBy.CreateUI(oUI);
}
}
GroupBy.prototype.onError = function (sender, args) {
alert('Error: ' + args.get_message() + '\n');
}
// JavaScript source code
You have to call clientContext.executeQueryAsync after calling clientContext.load in order to populate any results from the SharePoint object model.
executeQueryAsync takes two parameters: first the function to execute on success, and second the function to execute if an error is encountered. Any code that depends on successfully loading values from the query should be placed in the on success function.
Can someone please help me understand why the function writeOptions logs optionCounter twice?
console.log("<option values=" + optionCounter + ">"+optionCounter);
Why is there a second optionCounter placed after the option element?
<script type = "text/javascript">
function writeOptions(startNumber,endNumber)
{
var optionCounter;
for(optionCounter = startNumber;
optionCounter <= endNumber; optionCounter++)
{
document.write("<option value=" + optionCounter + ">" + optionCounter);
}
}
function writeMonthOptions()
{
var theMonth;
var monthCounter;
var theDate = new Date(1);
for(monthCounter = 0; monthCounter < 12; monthCounter++)
{
theDate.setMonth(monthCounter);
theMonth = theDate.toString();
theMonth = theMonth.substr(4,3);
document.write("<option value=" + theMonth + ">" + theMonth);
}
}
function recalcDateDiff()
{
var myForm = document.form1;
var firstDay =
myForm.firstDay.options[myForm.firstDay.selectedIndex].value;
var secondDay =
myForm.secondDay.options[myForm.secondDay.selectedIndex].value;
var firstMonth =
myForm.firstMonth.options[myForm.firstMonth.selectedIndex].value;
var secondMonth =
myForm.secondMonth.options[myForm.secondMonth.selectedIndex].value;
var firstYear =
myForm.firstYear.options[myForm.firstYear.selectedIndex].value;
var secondYear =
myForm.secondYear.options[myForm.secondYear.selectedIndex].value;
var firstDate =
new Date(firstDay + " " + firstMonth + " " + firstYear);
var secondDate = new Date(secondDay + " " + secondMonth + " " + secondYear);
var daysDiff = (secondDate.valueOf() - firstDate.valueOf());
daysDiff = Math.floor(Math.abs((((daysDiff/1000)/60)/60)/24));
myForm.txtDays.value = daysDiff;
}
function window_onload()
{
var theForm = document.form1;
var nowDate = new Date();
theForm.firstDay.options[nowDate.getDate() - 1].selected =true;
theForm.secondDay.options[nowDate.getDate() - 1].selected = true;
theForm.firstMonth.options[nowDate.getMonth() - 1].selected = true;
theForm.secondMonth.options[nowDate.getMonth() - 1].selected = true;
theForm.firstYear.options[nowDate.getFullYear() - 1970].selected = true;
theForm.secondYear.options[nowDate.getFullYear() - 1970].selected = true;
}
</script>
as you can see this is the entire Javascript codeblock for this particular example.
I believe you know HTML. Each <option> tag has a display text (or label) and a value. And your code is creating the html option tag with both. So, when you write:
document.write("<option value=" + optionCounter + ">" + optionCounter);
the first optionCounter is for value and second one is for label/display text.
Note: I don't see the option tag being closed which could result in issues if not handled properly by the browser, so modify the statement as follows to render correct HTML:
document.write("<option value=" + optionCounter + ">" + optionCounter + "</option>");
Refer more about select tag & option tag on w3schools.com.
I am recieving data (10 records at a time) and inserting it in a div in a javascript loop
var a1 = $('.HomeAnnoucement').length;
var a2 = $('.HomeAnnoucement').length;
for (a1 ; a1 < (+a2 + +data.d.length) ; a1++) {
var a = a1 - a2;
var newFormat = '<div class="HomeAnnoucement"><label class="annID" id="archannouncementID' + a1 + '" style="display: none;" /><div class="DateandDelete left"><a class="AnnoucementDate left"><strong>' + data.d[a].EffectiveDate.split('/')[1] + getPostWord(parseInt(data.d[a].EffectiveDate.split('/')[1])) + '</strong> ' + getMonthString(parseInt(data.d[a].EffectiveDate.split('/')[0])) + '</a><div class="clear"></div></div><a class="AnnoucementTitle left"><strong id="archannTitle' + a1 + '" class="bold"></strong></a><div class="clear"></div></div><div class="AnnoucementDescription" id="archannDescription' + a1 + '" style="display:none;"></div>';
$('#archivedAnnouncements').append(newFormat);
$('#archannouncementID' + a1).append(data.d[a].ID);
$('#archannTitle' + a1).append(data.d[a].Title);
if (data.d[a].Owner != "" && data.d[a].Owner != " ") {
$('#archannTitle' + a1).append('<label style="font-weight: normal !important;"> by ' + data.d[a].Owner + '</label>');
}
var description = data.d[a].Description.replace(/\"/g, "'");
var div = document.createElement("div");
div.innerHTML = description;
var descriptiontext = div.textContent || div.innerText || "";
$('#archannDescription' + a1).html(data.d[a].Description);
}
I want to add delay in between inserting the rows. So that the user could see each record insertion in the grid. I have tried inserting the elements with display: none and fadingIn setTimeOut function but that didnt work. Please help.
Use JQuery Show with animation
Here is sample quoted form page above
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button>Show it</button>
<p style="display: none">Hello 2</p>
<script>
$("button").click(function () {
$("p").show("slow");
});
</script>
</body>
</html>
In this case you can add hidden controls to child list, and call show with animation in loop
JQuery .delay() would help you
http://api.jquery.com/delay/
I've modified your existing code to hide each row and then set a delay and fadeIn...
var a1 = $('.HomeAnnoucement').length;
var a2 = $('.HomeAnnoucement').length;
for (a1 ; a1 < (+a2 + +data.d.length) ; a1++) {
var a = a1 - a2;
var $newFormat = $('<div class="HomeAnnoucement"><label class="annID" id="archannouncementID' + a1 + '" style="display: none;" /><div class="DateandDelete left"><a class="AnnoucementDate left"><strong>' + data.d[a].EffectiveDate.split('/')[1] + getPostWord(parseInt(data.d[a].EffectiveDate.split('/')[1])) + '</strong> ' + getMonthString(parseInt(data.d[a].EffectiveDate.split('/')[0])) + '</a><div class="clear"></div></div><a class="AnnoucementTitle left"><strong id="archannTitle' + a1 + '" class="bold"></strong></a><div class="clear"></div></div><div class="AnnoucementDescription" id="archannDescription' + a1 + '" style="display:none;"></div>');
$('#archivedAnnouncements').append($newFormat);
$('#archannouncementID' + a1).append(data.d[a].ID);
$('#archannTitle' + a1).append(data.d[a].Title);
if (data.d[a].Owner != "" && data.d[a].Owner != " ") {
$('#archannTitle' + a1).append('<label style="font-weight: normal !important;"> by ' + data.d[a].Owner + '</label>');
}
var description = data.d[a].Description.replace(/\"/g, "'");
var div = document.createElement("div");
div.innerHTML = description;
var descriptiontext = div.textContent || div.innerText || "";
$('#archannDescription' + a1).html(data.d[a].Description);
$newFormat.hide().delay(a * 500).fadeIn();
}