Firebase Web data ordering in container - javascript

I'm currently working on a Firebase project and I'm stuck on data ordering.
Here's my javascript code:
function displayContent() {
if (firstKey != null) {
var i = 0;
ref.orderByKey().endAt(firstKey).limitToLast(5).on("child_added", function(childSnapshot) {
var childType;
if (i == 0) {
firstKey = null;
childType = "lastChild";
} else {
childType = "firstChild";
}
i++;
if (i < 5) {
var containerElement = document.getElementsByClassName('post-container')[0];
if (childSnapshot.val().image != null) {
containerElement.insertBefore(
createPostElementImg(
childSnapshot.key,
childSnapshot.val().title,
childSnapshot.val().desc,
childSnapshot.val().image),
containerElement.childType);
if (firstKey == null) {
firstKey = childSnapshot.key;
console.log(firstKey);
}
} else {
containerElement.insertBefore(
createPostElement(
childSnapshot.key,
childSnapshot.val().title,
childSnapshot.val().desc),
containerElement.childType);
if (firstKey == null) {
firstKey = childSnapshot.key;
console.log(firstKey);
}
}
}
});
} else {
ref.orderByKey().limitToLast(5).on("child_added", function(childSnapshot) {
var containerElement = document.getElementsByClassName('post-container')[0];
if (childSnapshot.val().image != null) {
containerElement.insertBefore(
createPostElementImg(
childSnapshot.key,
childSnapshot.val().title,
childSnapshot.val().desc,
childSnapshot.val().image),
containerElement.firstChild);
if (firstKey == null) {
firstKey = childSnapshot.key;
console.log(firstKey);
}
} else {
containerElement.insertBefore(
createPostElement(
childSnapshot.key,
childSnapshot.val().title,
childSnapshot.val().desc),
containerElement.firstChild);
if (firstKey == null) {
firstKey = childSnapshot.key;
console.log(firstKey);
}
}
});
}
}
The first call, when the firstKey is equal to null is ordered properly, but the data loaded onScroll (when the firstKey is not null) is displayed in the wrong order. Is there any way to sort that data?
Thanks!
EDIT:
I have this piece of code for the detection of the page being scrolled to the bottom:
$(document).ready(function() {
var l_post = 0;
var n_post = 0;
var ref = firebase.database().ref().child('Blog');
ref.once("value", function(snapshot) {
n_post = snapshot.numChildren();
console.log(n_post);
});
jQuery(
function($)
{
$(".content").bind('scroll', function()
{
if($(this).scrollTop() + $(this).innerHeight()==$(this)[0].scrollHeight)
{
if(l_post < n_post) {
displayContent();
l_post = l_post + 5;
console.log(l_post);
}
}
})
}
);
});

Related

Javascript keyup function first keypress don't work two press worked

My code working but half working :(
The action that needs to be done is to execute various operations on the entered data and to write the collection. However, when the keys are pressed, the previous operation is performed.
Note: format.money and unformat in accounting js.
function inputkopyala(){
var t = $('#toplam').val();
if ($('#toplam1').val() == null) {
var t1 = 0;
}
else {
var t1 = $('#toplam1').val();
}
if ($('#toplam2').val() == null) {
var t2 = 0;
}
else {
var t2 = $('#toplam2').val();
}
if ($('#toplam3').val() == null) {
var t3 = 0;
}
else {
var t3 = $('#toplam3').val();
}
if ($('#toplam4').val() == null) {
var t4 = 0;
}
else {
var t4 = $('#toplam4').val();
}
if ($('#toplam5').val() == null) {
var t5 = 0;
}
else {
var t5 = $('#toplam5').val();
}
if ($('#toplam6').val() == null) {
var t6 = 0;
}
else {
var t6 = $('#toplam6').val();
}
if ($('#toplam7').val() == null) {
var t7 = 0;
}
else {
var t7 = $('#toplam7').val();
}
if ($('#toplam8').val() == null) {
var t8 = 0;
}
else {
var t8 = $('#toplam8').val();
}
if ($('#toplam9').val() == null) {
var t9 = 0;
}
else {
var t9 = $('#toplam9').val();
}
if ($('#toplam10').val() == null) {
var t10 = 0;
}
else {
var t10 = $('#toplam10').val();
}
if ($('#toplam11').val() == null) {
var t11 = 0;
}
else {
var t11 = $('#toplam11').val();
}
if ($('#toplam12').val() == null) {
var t12 = 0;
}
else {
var t12 = $('#toplam12').val();
}
if ($('#toplam13').val() == null) {
var t13 = 0;
}
else {
var t13 = $('#toplam13').val();
}
if ($('#toplam14').val() == null) {
var t14 = 0;
}
else {
var t14 = $('#toplam14').val();
}
if ($('#toplam15').val() == null) {
var t15 = 0;
}
else {
var t15 = $('#toplam15').val();
}
if ($('#toplam16').val() == null) {
var t16 = 0;
}
else {
var t16 = $('#toplam16').val();
}
if ($('#toplam17').val() == null) {
var t17 = 0;
}
else {
var t17 = $('#toplam17').val();
}
if ($('#toplam18').val() == null) {
var t18 = 0;
}
else {
var t18 = $('#toplam18').val();
}
if ($('#toplam19').val() == null) {
var t19 = 0;
}
else {
var t19 = $('#toplam19').val();
}
if ($('#toplam20').val() == null) {
var t20 = 0;
}
else {
var t20 = $('#toplam20').val();
}
if ($('#toplam21').val() == null) {
var t21 = 0;
}
else {
var t21 = $('#toplam21').val();
}
if ($('#toplam22').val() == null) {
var t22 = 0;
}
else {
var t22 = $('#toplam22').val();
}
if ($('#toplam23').val() == null) {
var t23 = 0;
}
else {
var t23 = $('#toplam23').val();
}
if ($('#toplam24').val() == null) {
var t24 = 0;
}
else {
var t24 = $('#toplam24').val();
}
if ($('#toplam25').val() == null) {
var t25 = 0;
}
else {
var t25 = $('#toplam25').val();
}
if ($('#toplam26').val() == null) {
var t26 = 0;
}
else {
var t26 = $('#toplam26').val();
}
if ($('#toplam27').val() == null) {
var t27 = 0;
}
else {
var t27 = $('#toplam27').val();
}
if ($('#toplam28').val() == null) {
var t28 = 0;
}
else {
var t28 = $('#toplam28').val();
}
if ($('#toplam29').val() == null) {
var t29 = 0;
}
else {
var t29 = $('#toplam29').val();
}
if ($('#toplam30').val() == null) {
var t30 = 0;
}
else {
var t30 = $('#toplam30').val();
}
var sonuc;
sonuc = accounting.formatMoney(accounting.unformat(t)+accounting.unformat(t1)+accounting.unformat(t2)+accounting.unformat(t3)+accounting.unformat(t4)+accounting.unformat(t5)+accounting.unformat(t6)+accounting.unformat(t7)+accounting.unformat(t8)+accounting.unformat(t9)+accounting.unformat(t10)+accounting.unformat(t11)+accounting.unformat(t12)+accounting.unformat(t13)+accounting.unformat(t14)+accounting.unformat(t15)+accounting.unformat(t16)+accounting.unformat(t17)+accounting.unformat(t18)+accounting.unformat(t19)+accounting.unformat(t20)+accounting.unformat(t21)+accounting.unformat(t22)+accounting.unformat(t23)+accounting.unformat(t24)+accounting.unformat(t25)+accounting.unformat(t26)+accounting.unformat(t27)+accounting.unformat(t28)+accounting.unformat(t29)+accounting.unformat(t30));
$('#yekun').html(""+sonuc +"");
var v = $('#vergi').val();
if ($('#vergi1').val() == null) {
var v1 = 0;
}
else {
var v1 = $('#vergi1').val();
}
if ($('#vergi2').val() == null) {
var v2 = 0;
}
else {
var v2 = $('#vergi2').val();
}
if ($('#vergi3').val() == null) {
var v3 = 0;
}
else {
var v3 = $('#vergi3').val();
}
if ($('#vergi4').val() == null) {
var v4 = 0;
}
else {
var v4 = $('#vergi4').val();
}
if ($('#vergi5').val() == null) {
var v5 = 0;
}
else {
var v5 = $('#vergi5').val();
}
if ($('#vergi6').val() == null) {
var v6 = 0;
}
else {
var v6 = $('#vergi6').val();
}
if ($('#vergi7').val() == null) {
var v7 = 0;
}
else {
var v7 = $('#vergi7').val();
}
if ($('#vergi8').val() == null) {
var v8 = 0;
}
else {
var v8 = $('#vergi8').val();
}
if ($('#vergi9').val() == null) {
var v9 = 0;
}
else {
var v9 = $('#vergi9').val();
}
if ($('#vergi10').val() == null) {
var v10 = 0;
}
else {
var v10 = $('#vergi10').val();
}
if ($('#vergi11').val() == null) {
var v11 = 0;
}
else {
var v11 = $('#vergi11').val();
}
if ($('#vergi12').val() == null) {
var v12 = 0;
}
else {
var v12 = $('#vergi12').val();
}
if ($('#vergi13').val() == null) {
var v13 = 0;
}
else {
var v13 = $('#vergi13').val();
}
if ($('#vergi14').val() == null) {
var v14 = 0;
}
else {
var v14 = $('#vergi14').val();
}
if ($('#vergi15').val() == null) {
var v15 = 0;
}
else {
var v15 = $('#vergi15').val();
}
if ($('#vergi16').val() == null) {
var v16 = 0;
}
else {
var v16 = $('#vergi16').val();
}
if ($('#vergi17').val() == null) {
var v17 = 0;
}
else {
var v17 = $('#vergi17').val();
}
if ($('#vergi18').val() == null) {
var v18 = 0;
}
else {
var v18 = $('#vergi18').val();
}
if ($('#vergi19').val() == null) {
var v19 = 0;
}
else {
var v19 = $('#vergi19').val();
}
if ($('#vergi20').val() == null) {
var v20 = 0;
}
else {
var v20 = $('#vergi20').val();
}
if ($('#vergi21').val() == null) {
var v21 = 0;
}
else {
var v21 = $('#vergi21').val();
}
if ($('#vergi22').val() == null) {
var v22 = 0;
}
else {
var v22 = $('#vergi22').val();
}
if ($('#vergi23').val() == null) {
var v23 = 0;
}
else {
var v23 = $('#vergi23').val();
}
if ($('#vergi24').val() == null) {
var v24 = 0;
}
else {
var v24 = $('#vergi24').val();
}
if ($('#vergi25').val() == null) {
var v25 = 0;
}
else {
var v25 = $('#vergi25').val();
}
if ($('#vergi26').val() == null) {
var v26 = 0;
}
else {
var v26 = $('#vergi26').val();
}
if ($('#vergi27').val() == null) {
var v27 = 0;
}
else {
var v27 = $('#vergi27').val();
}
if ($('#vergi28').val() == null) {
var v28 = 0;
}
else {
var v28 = $('#vergi28').val();
}
if ($('#vergi29').val() == null) {
var v29 = 0;
}
else {
var v29 = $('#vergi29').val();
}
if ($('#vergi30').val() == null) {
var v30 = 0;
}
else {
var v30 = $('#vergi30').val();
}
var vergiler;
vergiler = accounting.formatMoney(accounting.unformat(v)+accounting.unformat(v1)+accounting.unformat(v2)+accounting.unformat(v3)+accounting.unformat(v4)+accounting.unformat(v5)+accounting.unformat(v6)+accounting.unformat(v7)+accounting.unformat(v8)+accounting.unformat(v9)+accounting.unformat(v10)+accounting.unformat(v11)+accounting.unformat(v12)+accounting.unformat(v13)+accounting.unformat(v14)+accounting.unformat(v15)+accounting.unformat(v16)+accounting.unformat(v17)+accounting.unformat(v18)+accounting.unformat(v19)+accounting.unformat(v20)+accounting.unformat(v21)+accounting.unformat(v22)+accounting.unformat(v23)+accounting.unformat(v24)+accounting.unformat(v25)+accounting.unformat(v26)+accounting.unformat(v27)+accounting.unformat(v28)+accounting.unformat(v29)+accounting.unformat(v30));
$('#topkdv').html(""+vergiler +"");
document.urunformu.toplam.value = accounting.formatMoney(document.urunformu.adet.value*document.urunformu.birimfiyat.value)
document.urunformu.vergi.value = accounting.formatMoney(document.urunformu.adet.value*document.urunformu.birimfiyat.value*document.urunformu.vergioran.value/100)
document.getElementById("geneltoplam").innerHTML = accounting.formatMoney(accounting.unformat(document.getElementById("yekun").innerHTML)+accounting.unformat(document.getElementById("topkdv").innerHTML))
}
function inputkopyala1(){
var t = $('#toplam').val();
if ($('#toplam1').val() == null) {
var t1 = 0;
}
else {
var t1 = $('#toplam1').val();
}
if ($('#toplam2').val() == null) {
var t2 = 0;
}
else {
var t2 = $('#toplam2').val();
}
if ($('#toplam3').val() == null) {
var t3 = 0;
}
else {
var t3 = $('#toplam3').val();
}
if ($('#toplam4').val() == null) {
var t4 = 0;
}
else {
var t4 = $('#toplam4').val();
}
if ($('#toplam5').val() == null) {
var t5 = 0;
}
else {
var t5 = $('#toplam5').val();
}
if ($('#toplam6').val() == null) {
var t6 = 0;
}
else {
var t6 = $('#toplam6').val();
}
if ($('#toplam7').val() == null) {
var t7 = 0;
}
else {
var t7 = $('#toplam7').val();
}
if ($('#toplam8').val() == null) {
var t8 = 0;
}
else {
var t8 = $('#toplam8').val();
}
if ($('#toplam9').val() == null) {
var t9 = 0;
}
else {
var t9 = $('#toplam9').val();
}
if ($('#toplam10').val() == null) {
var t10 = 0;
}
else {
var t10 = $('#toplam10').val();
}
if ($('#toplam11').val() == null) {
var t11 = 0;
}
else {
var t11 = $('#toplam11').val();
}
if ($('#toplam12').val() == null) {
var t12 = 0;
}
else {
var t12 = $('#toplam12').val();
}
if ($('#toplam13').val() == null) {
var t13 = 0;
}
else {
var t13 = $('#toplam13').val();
}
if ($('#toplam14').val() == null) {
var t14 = 0;
}
else {
var t14 = $('#toplam14').val();
}
if ($('#toplam15').val() == null) {
var t15 = 0;
}
else {
var t15 = $('#toplam15').val();
}
if ($('#toplam16').val() == null) {
var t16 = 0;
}
else {
var t16 = $('#toplam16').val();
}
if ($('#toplam17').val() == null) {
var t17 = 0;
}
else {
var t17 = $('#toplam17').val();
}
if ($('#toplam18').val() == null) {
var t18 = 0;
}
else {
var t18 = $('#toplam18').val();
}
if ($('#toplam19').val() == null) {
var t19 = 0;
}
else {
var t19 = $('#toplam19').val();
}
if ($('#toplam20').val() == null) {
var t20 = 0;
}
else {
var t20 = $('#toplam20').val();
}
if ($('#toplam21').val() == null) {
var t21 = 0;
}
else {
var t21 = $('#toplam21').val();
}
if ($('#toplam22').val() == null) {
var t22 = 0;
}
else {
var t22 = $('#toplam22').val();
}
if ($('#toplam23').val() == null) {
var t23 = 0;
}
else {
var t23 = $('#toplam23').val();
}
if ($('#toplam24').val() == null) {
var t24 = 0;
}
else {
var t24 = $('#toplam24').val();
}
if ($('#toplam25').val() == null) {
var t25 = 0;
}
else {
var t25 = $('#toplam25').val();
}
if ($('#toplam26').val() == null) {
var t26 = 0;
}
else {
var t26 = $('#toplam26').val();
}
if ($('#toplam27').val() == null) {
var t27 = 0;
}
else {
var t27 = $('#toplam27').val();
}
if ($('#toplam28').val() == null) {
var t28 = 0;
}
else {
var t28 = $('#toplam28').val();
}
if ($('#toplam29').val() == null) {
var t29 = 0;
}
else {
var t29 = $('#toplam29').val();
}
if ($('#toplam30').val() == null) {
var t30 = 0;
}
else {
var t30 = $('#toplam30').val();
}
var sonuc;
sonuc = accounting.formatMoney(accounting.unformat(t)+accounting.unformat(t1)+accounting.unformat(t2)+accounting.unformat(t3)+accounting.unformat(t4)+accounting.unformat(t5)+accounting.unformat(t6)+accounting.unformat(t7)+accounting.unformat(t8)+accounting.unformat(t9)+accounting.unformat(t10)+accounting.unformat(t11)+accounting.unformat(t12)+accounting.unformat(t13)+accounting.unformat(t14)+accounting.unformat(t15)+accounting.unformat(t16)+accounting.unformat(t17)+accounting.unformat(t18)+accounting.unformat(t19)+accounting.unformat(t20)+accounting.unformat(t21)+accounting.unformat(t22)+accounting.unformat(t23)+accounting.unformat(t24)+accounting.unformat(t25)+accounting.unformat(t26)+accounting.unformat(t27)+accounting.unformat(t28)+accounting.unformat(t29)+accounting.unformat(t30));
var v = $('#vergi').val();
if ($('#vergi1').val() == null) {
var v1 = 0;
}
else {
var v1 = $('#vergi1').val();
}
if ($('#vergi2').val() == null) {
var v2 = 0;
}
else {
var v2 = $('#vergi2').val();
}
if ($('#vergi3').val() == null) {
var v3 = 0;
}
else {
var v3 = $('#vergi3').val();
}
if ($('#vergi4').val() == null) {
var v4 = 0;
}
else {
var v4 = $('#vergi4').val();
}
if ($('#vergi5').val() == null) {
var v5 = 0;
}
else {
var v5 = $('#vergi5').val();
}
if ($('#vergi6').val() == null) {
var v6 = 0;
}
else {
var v6 = $('#vergi6').val();
}
if ($('#vergi7').val() == null) {
var v7 = 0;
}
else {
var v7 = $('#vergi7').val();
}
if ($('#vergi8').val() == null) {
var v8 = 0;
}
else {
var v8 = $('#vergi8').val();
}
if ($('#vergi9').val() == null) {
var v9 = 0;
}
else {
var v9 = $('#vergi9').val();
}
if ($('#vergi10').val() == null) {
var v10 = 0;
}
else {
var v10 = $('#vergi10').val();
}
if ($('#vergi11').val() == null) {
var v11 = 0;
}
else {
var v11 = $('#vergi11').val();
}
if ($('#vergi12').val() == null) {
var v12 = 0;
}
else {
var v12 = $('#vergi12').val();
}
if ($('#vergi13').val() == null) {
var v13 = 0;
}
else {
var v13 = $('#vergi13').val();
}
if ($('#vergi14').val() == null) {
var v14 = 0;
}
else {
var v14 = $('#vergi14').val();
}
if ($('#vergi15').val() == null) {
var v15 = 0;
}
else {
var v15 = $('#vergi15').val();
}
if ($('#vergi16').val() == null) {
var v16 = 0;
}
else {
var v16 = $('#vergi16').val();
}
if ($('#vergi17').val() == null) {
var v17 = 0;
}
else {
var v17 = $('#vergi17').val();
}
if ($('#vergi18').val() == null) {
var v18 = 0;
}
else {
var v18 = $('#vergi18').val();
}
if ($('#vergi19').val() == null) {
var v19 = 0;
}
else {
var v19 = $('#vergi19').val();
}
if ($('#vergi20').val() == null) {
var v20 = 0;
}
else {
var v20 = $('#vergi20').val();
}
if ($('#vergi21').val() == null) {
var v21 = 0;
}
else {
var v21 = $('#vergi21').val();
}
if ($('#vergi22').val() == null) {
var v22 = 0;
}
else {
var v22 = $('#vergi22').val();
}
if ($('#vergi23').val() == null) {
var v23 = 0;
}
else {
var v23 = $('#vergi23').val();
}
if ($('#vergi24').val() == null) {
var v24 = 0;
}
else {
var v24 = $('#vergi24').val();
}
if ($('#vergi25').val() == null) {
var v25 = 0;
}
else {
var v25 = $('#vergi25').val();
}
if ($('#vergi26').val() == null) {
var v26 = 0;
}
else {
var v26 = $('#vergi26').val();
}
if ($('#vergi27').val() == null) {
var v27 = 0;
}
else {
var v27 = $('#vergi27').val();
}
if ($('#vergi28').val() == null) {
var v28 = 0;
}
else {
var v28 = $('#vergi28').val();
}
if ($('#vergi29').val() == null) {
var v29 = 0;
}
else {
var v29 = $('#vergi29').val();
}
if ($('#vergi30').val() == null) {
var v30 = 0;
}
else {
var v30 = $('#vergi30').val();
}
var vergiler;
vergiler = accounting.formatMoney(accounting.unformat(v)+accounting.unformat(v1)+accounting.unformat(v2)+accounting.unformat(v3)+accounting.unformat(v4)+accounting.unformat(v5)+accounting.unformat(v6)+accounting.unformat(v7)+accounting.unformat(v8)+accounting.unformat(v9)+accounting.unformat(v10)+accounting.unformat(v11)+accounting.unformat(v12)+accounting.unformat(v13)+accounting.unformat(v14)+accounting.unformat(v15)+accounting.unformat(v16)+accounting.unformat(v17)+accounting.unformat(v18)+accounting.unformat(v19)+accounting.unformat(v20)+accounting.unformat(v21)+accounting.unformat(v22)+accounting.unformat(v23)+accounting.unformat(v24)+accounting.unformat(v25)+accounting.unformat(v26)+accounting.unformat(v27)+accounting.unformat(v28)+accounting.unformat(v29)+accounting.unformat(v30));
document.urunformu.toplam1.value = accounting.formatMoney(document.urunformu.adet1.value*document.urunformu.birimfiyat1.value)
document.urunformu.vergi1.value = accounting.formatMoney(document.urunformu.adet1.value*document.urunformu.birimfiyat1.value*document.urunformu.vergioran1.value/100)
$('#topkdv').html(""+vergiler +"");
$('#yekun').html(""+sonuc +"");
document.getElementById("geneltoplam").innerHTML = accounting.formatMoney(accounting.unformat(document.getElementById("yekun").innerHTML)+accounting.unformat(document.getElementById("topkdv").innerHTML))
}
//note: function inputkopyala2,3,4... continues to 29
<a href="javascript:void(0);" id="add_more" class="dt-button buttons-print btn btn-cerceve btn-xs ml">
<i class="fa fa-plus"></i>
<b>Add New</b>
</a>
<script type="text/javascript">
$(document).ready(function () {
var maxAppend = 0;
var degisken = 1;
$("#add_more").click(function () {
if (maxAppend >= 29) {
alert("Maksimum Satır Sayısına Ulaştınız");
}
else {
var add_new = $('<tr style=""><td><input type="text" name="item_name[]" required placeholder="Ürün Adı" class="form-control"></td>\n\
<td><textarea style="height:40px;" rows="1" name="item_desc[]" placeholder="Ürün Açıklaması" class="form-control"></textarea></td>\n\
<td class="col-sm-1"><input onkeyup="inputkopyala' +degisken+ '()" onkeypress="return isNumberKey(event)" id="adet' +degisken+ '" type="text" data-parsley-type="number" name="quantity[]" placeholder="1" required class="form-control"></td>">\n\
<td class="col-sm-1"><input onkeyup="inputkopyala' +degisken+ '()" onkeypress="return isNumberKey(event)" id="birimfiyat' +degisken+ '" type="text" data-parsley-type="number" name="unit_cost[]" required placeholder="100 ₺" class="form-control"></td>\n\
<td class="col-sm-1"><select onchange="inputkopyala' +degisken+ '()" id="vergioran' +degisken+ '" name="item_tax_rate[]" class="form-control"><option value="0.00"><?= lang('none') ?></option>\n\\n\
<?php
$tax_rates = $this->db->get('tbl_tax_rates')->result();
if (!empty($tax_rates)) {
foreach ($tax_rates as $v_tax) {
?><option value="<?= $v_tax->tax_rate_percent ?>"><?= $v_tax->tax_rate_name ?></option><?php
}
}
?></select></td>\n\
<td class="col-sm-1"><input id="vergi' +degisken+ '" type="text" name="tax" placeholder="0,00 ₺" readonly="" class="form-control"></td>\n\
<td class="col-sm-2"><input id="toplam' +degisken+ '" type="text" value="" name="tax" placeholder="0,00 ₺" readonly="" class="form-control toplam"></td>\n\
<td><i class="fa fa-times"></i></strong></td></tr>\n<br/>');
degisken++;
maxAppend++;
$("#add_new").append(add_new);
}
});
$("#add_new").on('click', '.remCF', function () {
$(this).parent().parent().remove();
degisken--;
maxAppend--;
});
});
</script>

sessionStorage data not persisting in another or new tab

I am using sessionStorage to get some data and able to use it to create a link and append it to the page.
(function() {
var rep_info = document.getElementById('rep-info'),
session = sessionStorage.getItem('ngStorage-getRepInfo'),
obj = JSON.parse(session),
vanity_name = obj.profile.data.vanityName,
your_URL = 'https://foo.com/';
console.log(obj.profile.data.vanityName);
rep_info.insertAdjacentHTML('afterbegin', 'foo.com/' + vanity_name + '');
})();
However if I copy and paste the URL of the page which contains the script above, it doesn't fire. Instead I get this error.
Uncaught TypeError: Cannot read property 'profile' of null
But when I do a refresh, the script fires.
I should mention this page/site is accessed via user authentification i.e. username & password.
I found this solution, but I couldn't figure out how to get it going.
Thanks in advance!
UPDATE 2-1-2017
I included the library I referenced and my attempt at using to solve my problem, it's right after the module.
var LocalStoreManager = (function() {
function LocalStoreManager() {
var _this = this;
this.syncKeys = [];
this.reservedKeys = ['sync_keys', 'addToSyncKeys', 'removeFromSyncKeys',
'getSessionStorage', 'setSessionStorage', 'addToSessionStorage', 'removeFromSessionStorage', 'clearAllSessionsStorage', 'raiseDBEvent'
];
this.sessionStorageTransferHandler = function(event) {
if (!event.newValue)
return;
if (event.key == 'getSessionStorage') {
if (sessionStorage.length) {
localStorage.setItem('setSessionStorage', JSON.stringify(sessionStorage));
localStorage.removeItem('setSessionStorage');
}
} else if (event.key == 'setSessionStorage') {
if (!_this.syncKeys.length)
_this.loadSyncKeys();
var data = JSON.parse(event.newValue);
for (var key in data) {
if (_this.syncKeysContains(key))
sessionStorage.setItem(key, data[key]);
}
} else if (event.key == 'addToSessionStorage') {
var data = JSON.parse(event.newValue);
_this.addToSessionStorageHelper(data["data"], data["key"]);
} else if (event.key == 'removeFromSessionStorage') {
_this.removeFromSessionStorageHelper(event.newValue);
} else if (event.key == 'clearAllSessionsStorage' && sessionStorage.length) {
_this.clearInstanceSessionStorage();
} else if (event.key == 'addToSyncKeys') {
_this.addToSyncKeysHelper(event.newValue);
} else if (event.key == 'removeFromSyncKeys') {
_this.removeFromSyncKeysHelper(event.newValue);
}
};
}
//Todo: Implement EventListeners for the various event operations and a SessionStorageEvent for specific data keys
LocalStoreManager.prototype.initialiseStorageSyncListener = function() {
if (LocalStoreManager.syncListenerInitialised == true)
return;
LocalStoreManager.syncListenerInitialised = true;
window.addEventListener("storage", this.sessionStorageTransferHandler, false);
this.syncSessionStorage();
};
LocalStoreManager.prototype.deinitialiseStorageSyncListener = function() {
window.removeEventListener("storage", this.sessionStorageTransferHandler, false);
LocalStoreManager.syncListenerInitialised = false;
};
LocalStoreManager.prototype.syncSessionStorage = function() {
localStorage.setItem('getSessionStorage', '_dummy');
localStorage.removeItem('getSessionStorage');
};
LocalStoreManager.prototype.clearAllStorage = function() {
this.clearAllSessionsStorage();
this.clearLocalStorage();
};
LocalStoreManager.prototype.clearAllSessionsStorage = function() {
this.clearInstanceSessionStorage();
localStorage.removeItem(LocalStoreManager.DBKEY_SYNC_KEYS);
localStorage.setItem('clearAllSessionsStorage', '_dummy');
localStorage.removeItem('clearAllSessionsStorage');
};
LocalStoreManager.prototype.clearInstanceSessionStorage = function() {
sessionStorage.clear();
this.syncKeys = [];
};
LocalStoreManager.prototype.clearLocalStorage = function() {
localStorage.clear();
};
LocalStoreManager.prototype.addToSessionStorage = function(data, key) {
this.addToSessionStorageHelper(data, key);
this.addToSyncKeysBackup(key);
localStorage.setItem('addToSessionStorage', JSON.stringify({ key: key, data: data }));
localStorage.removeItem('addToSessionStorage');
};
LocalStoreManager.prototype.addToSessionStorageHelper = function(data, key) {
this.addToSyncKeysHelper(key);
sessionStorage.setItem(key, data);
};
LocalStoreManager.prototype.removeFromSessionStorage = function(keyToRemove) {
this.removeFromSessionStorageHelper(keyToRemove);
this.removeFromSyncKeysBackup(keyToRemove);
localStorage.setItem('removeFromSessionStorage', keyToRemove);
localStorage.removeItem('removeFromSessionStorage');
};
LocalStoreManager.prototype.removeFromSessionStorageHelper = function(keyToRemove) {
sessionStorage.removeItem(keyToRemove);
this.removeFromSyncKeysHelper(keyToRemove);
};
LocalStoreManager.prototype.testForInvalidKeys = function(key) {
if (!key)
throw new Error("key cannot be empty");
if (this.reservedKeys.some(function(x) {
return x == key;
}))
throw new Error("The storage key \"" + key + "\" is reserved and cannot be used. Please use a different key");
};
LocalStoreManager.prototype.syncKeysContains = function(key) {
return this.syncKeys.some(function(x) {
return x == key;
});
};
LocalStoreManager.prototype.loadSyncKeys = function() {
if (this.syncKeys.length)
return;
this.syncKeys = this.getSyncKeysFromStorage();
};
LocalStoreManager.prototype.getSyncKeysFromStorage = function(defaultValue) {
if (defaultValue === void 0) { defaultValue = []; }
var data = localStorage.getItem(LocalStoreManager.DBKEY_SYNC_KEYS);
if (data == null)
return defaultValue;
else
return JSON.parse(data);
};
LocalStoreManager.prototype.addToSyncKeys = function(key) {
this.addToSyncKeysHelper(key);
this.addToSyncKeysBackup(key);
localStorage.setItem('addToSyncKeys', key);
localStorage.removeItem('addToSyncKeys');
};
LocalStoreManager.prototype.addToSyncKeysBackup = function(key) {
var storedSyncKeys = this.getSyncKeysFromStorage();
if (!storedSyncKeys.some(function(x) {
return x == key;
})) {
storedSyncKeys.push(key);
localStorage.setItem(LocalStoreManager.DBKEY_SYNC_KEYS, JSON.stringify(storedSyncKeys));
}
};
LocalStoreManager.prototype.removeFromSyncKeysBackup = function(key) {
var storedSyncKeys = this.getSyncKeysFromStorage();
var index = storedSyncKeys.indexOf(key);
if (index > -1) {
storedSyncKeys.splice(index, 1);
localStorage.setItem(LocalStoreManager.DBKEY_SYNC_KEYS, JSON.stringify(storedSyncKeys));
}
};
LocalStoreManager.prototype.addToSyncKeysHelper = function(key) {
if (!this.syncKeysContains(key))
this.syncKeys.push(key);
};
LocalStoreManager.prototype.removeFromSyncKeys = function(key) {
this.removeFromSyncKeysHelper(key);
this.removeFromSyncKeysBackup(key);
localStorage.setItem('removeFromSyncKeys', key);
localStorage.removeItem('removeFromSyncKeys');
};
LocalStoreManager.prototype.removeFromSyncKeysHelper = function(key) {
var index = this.syncKeys.indexOf(key);
if (index > -1) {
this.syncKeys.splice(index, 1);
}
};
LocalStoreManager.prototype.saveSessionData = function(data, key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
this.removeFromSyncKeys(key);
localStorage.removeItem(key);
sessionStorage.setItem(key, data);
};
LocalStoreManager.prototype.saveSyncedSessionData = function(data, key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
localStorage.removeItem(key);
this.addToSessionStorage(data, key);
};
LocalStoreManager.prototype.savePermanentData = function(data, key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
this.removeFromSessionStorage(key);
localStorage.setItem(key, data);
};
LocalStoreManager.prototype.moveDataToSessionStorage = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = this.getData(key);
if (data == null)
return;
this.saveSessionData(data, key);
};
LocalStoreManager.prototype.moveDataToSyncedSessionStorage = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = this.getData(key);
if (data == null)
return;
this.saveSyncedSessionData(data, key);
};
LocalStoreManager.prototype.moveDataToPermanentStorage = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = this.getData(key);
if (data == null)
return;
this.savePermanentData(data, key);
};
LocalStoreManager.prototype.getData = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = sessionStorage.getItem(key);
if (data == null)
data = localStorage.getItem(key);
return data;
};
LocalStoreManager.prototype.getDataObject = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
var data = this.getData(key);
if (data != null)
return JSON.parse(data);
else
return null;
};
LocalStoreManager.prototype.deleteData = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
this.removeFromSessionStorage(key);
localStorage.removeItem(key);
};
return LocalStoreManager;
})();
(function() {
var localStorageMangerInstance = new LocalStoreManager();
localStorageMangerInstance.initialiseStorageSyncListener();
var data = localStorageMangerInstance.getData('ngStorage-getRepInfo'),
obj = JSON.parse(data),
vanity_name = obj.profile.data.vanityName;
localStorageMangerInstance.saveSyncedSessionData(obj, obj.profile.data.vanityName);
var rep_info = document.getElementById('rep-info'),
your_avon_URL = 'https://youravon.com/';
rep_info.insertAdjacentHTML('afterbegin', 'youravon.com/' + vanity_name + '');
console.log(vanity_name);
console.log(obj.profile.data.vanityName);
})();

How can i set customize Form in add event of wdCalender?

i want to set my own customize form in wdCalendar add event like first name last name instead of "what". where in jquery.calendar.js i find quickadd function which one is used when user click on calendar to add event then form appear help of quickadd function but i dont know how to set custom field in this function so please help me
below one is quickadd function of jquery.calender.js
function quickadd(start, end, isallday, pos) {
if ((!option.quickAddHandler && option.quickAddUrl == "") || option.readonly) {
return;
}
var buddle = $("#bbit-cal-buddle");
if (buddle.length == 0) {
var temparr = [];
temparr.push('<div id="bbit-cal-buddle" style="z-index: 180; width: 400px;visibility:hidden;" class="bubble">');
temparr.push('<table class="bubble-table" cellSpacing="0" cellPadding="0"><tbody><tr><td class="bubble-cell-side"><div id="tl1" class="bubble-corner"><div class="bubble-sprite bubble-tl"></div></div>');
temparr.push('<td class="bubble-cell-main"><div class="bubble-top"></div><td class="bubble-cell-side"><div id="tr1" class="bubble-corner"><div class="bubble-sprite bubble-tr"></div></div> <tr><td class="bubble-mid" colSpan="3"><div style="overflow: hidden" id="bubbleContent1"><div><div></div><div class="cb-root">');
temparr.push('<table class="cb-table" cellSpacing="0" cellPadding="0"><tbody><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.time, ':</th><td class=cb-value><div id="bbit-cal-buddle-timeshow"></div></td></tr><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.content, ':</th><td class="cb-value"><div class="textbox-fill-wrapper"><div class="textbox-fill-mid"><input id="bbit-cal-what" class="textbox-fill-input"/></div></div><div class="cb-example">');
temparr.push(i18n.xgcalendar.example, '</div></td></tr></tbody></table><input id="bbit-cal-start" type="hidden"/><input id="bbit-cal-end" type="hidden"/><input id="bbit-cal-allday" type="hidden"/><input id="bbit-cal-quickAddBTN" value="');
temparr.push(i18n.xgcalendar.create_event, '" type="button"/> <SPAN id="bbit-cal-editLink" class="lk">');
temparr.push(i18n.xgcalendar.update_detail, ' <StrONG>>></StrONG></SPAN></div></div></div><tr><td><div id="bl1" class="bubble-corner"><div class="bubble-sprite bubble-bl"></div></div><td><div class="bubble-bottom"></div><td><div id="br1" class="bubble-corner"><div class="bubble-sprite bubble-br"></div></div></tr></tbody></table><div id="bubbleClose1" class="bubble-closebutton"></div><div id="prong2" class="prong"><div class=bubble-sprite></div></div></div>');
var tempquickAddHanler = temparr.join("");
temparr = null;
$(document.body).append(tempquickAddHanler);
buddle = $("#bbit-cal-buddle");
var calbutton = $("#bbit-cal-quickAddBTN");
var lbtn = $("#bbit-cal-editLink");
var closebtn = $("#bubbleClose1").click(function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
calbutton.click(function(e) {
if (option.isloading) {
return false;
}
option.isloading = true;
var what = $("#bbit-cal-what").val();
var datestart = $("#bbit-cal-start").val();
var dateend = $("#bbit-cal-end").val();
var allday = $("#bbit-cal-allday").val();
var f = /^[^\$\<\>]+$/.test(what);
if (!f) {
alert(i18n.xgcalendar.invalid_title);
$("#bbit-cal-what").focus();
option.isloading = false;
return false;
}
var zone = new Date().getTimezoneOffset() / 60 * -1;
var param = [{ "name": "CalendarTitle", value: what },
{ "name": "CalendarStartTime", value: datestart },
{ "name": "CalendarEndTime", value: dateend },
{ "name": "IsAllDayEvent", value: allday },
{ "name": "timezone", value: zone}];
if (option.extParam) {
for (var pi = 0; pi < option.extParam.length; pi++) {
param[param.length] = option.extParam[pi];
}
}
if (option.quickAddHandler && $.isFunction(option.quickAddHandler)) {
option.quickAddHandler.call(this, param);
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
else {
$("#bbit-cal-buddle").css("visibility", "hidden");
var newdata = [];
var tId = -1;
option.onBeforeRequestData && option.onBeforeRequestData(2);
$.post(option.quickAddUrl, param, function(data) {
if (data) {
if (data.IsSuccess == true) {
option.isloading = false;
option.eventItems[tId][0] = data.Data;
option.eventItems[tId][8] = 1;
render();
option.onAfterRequestData && option.onAfterRequestData(2);
}
else {
option.onRequestDataError && option.onRequestDataError(2, data);
option.isloading = false;
option.onAfterRequestData && option.onAfterRequestData(2);
}
}
}, "json");
newdata.push(-1, what);
var sd = strtodate(datestart);
var ed = strtodate(dateend);
var diff = DateDiff("d", sd, ed);
newdata.push(sd, ed, allday == "1" ? 1 : 0, diff > 0 ? 1 : 0, 0);
newdata.push(-1, 0, "", "");
tId = Ind(newdata);
realsedragevent();
render();
}
});
lbtn.click(function(e) {
if (!option.EditCmdhandler) {
alert("EditCmdhandler" + i18n.xgcalendar.i_undefined);
}
else {
if (option.EditCmdhandler && $.isFunction(option.EditCmdhandler)) {
option.EditCmdhandler.call(this, ['0', $("#bbit-cal-what").val(), $("#bbit-cal-start").val(), $("#bbit-cal-end").val(), $("#bbit-cal-allday").val()]);
}
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
return false;
});
buddle.mousedown(function(e) { return false });
}
var dateshow = CalDateShow(start, end, !isallday, true);
var off = getbuddlepos(pos.left, pos.top);
if (off.hide) {
$("#prong2").hide()
}
else {
$("#prong2").show()
}
$("#bbit-cal-buddle-timeshow").html(dateshow);
var calwhat = $("#bbit-cal-what").val("");
$("#bbit-cal-allday").val(isallday ? "1" : "0");
$("#bbit-cal-start").val(dateFormat.call(start, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
$("#bbit-cal-end").val(dateFormat.call(end, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
buddle.css({ "visibility": "visible", left: off.left, top: off.top });
calwhat.blur().focus(); //add 2010-01-26 blur() fixed chrome
$(document).one("mousedown", function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
return false;
}
could i add ajax link on add event and display custom form and add data to database ?
is there any solution of this type to direct open popup as in add event as like open in edit event ?
And Here we go..
just copy paste this code in your jquery.form.js
it will provide you and extra field to input text.
jquery.form.js
<script>
(function($) {
$.fn.ajaxSubmit = function(options) {
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function')
options = { success: options };
options = $.extend({
url: this.attr('action') || window.location.toString(),
type: this.attr('method') || 'GET'
}, options || {});
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (var n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n])
a.push( { name: n, value: options.data[n][k] } )
}
else
a.push( { name: n, value: options.data[n] } );
}
}
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null;
}
else
options.data = q;
var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i].apply(options, [data, status, $form]);
};
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
if (options.iframe || found) {
if ($.browser.safari && options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);
this.trigger('form-submit-notify', [this, options]);
return this;
function fileUpload() {
var form = $form[0];
if ($(':input[#name=submit]', form).length) {
alert('Error: Form elements must not be named "submit".');
return;
}
var opts = $.extend({}, $.ajaxSettings, options);
var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);
var id = 'jqFormIO' + (new Date().getTime());
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];
if ($.browser.msie || $.browser.opera)
io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = {
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function() {
this.aborted = 1;
$io.attr('src','about:blank');
}
};
var g = opts.global;
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);
if (s.beforeSend && s.beforeSend(xhr, s) === false) {
s.global && jQuery.active--;
return;
}
if (xhr.aborted)
return;
var cbInvoked = 0;
var timedOut = 0;
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
options.extraData = options.extraData || {};
options.extraData[n] = sub.value;
if (sub.type == "image") {
options.extraData[name+'.x'] = form.clk_x;
options.extraData[name+'.y'] = form.clk_y;
}
}
}
setTimeout(function() {
var t = $form.attr('target'), a = $form.attr('action');
$form.attr({
target: id,
method: 'POST',
action: opts.url
});
if (! options.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
var extraInputs = [];
try {
if (options.extraData)
for (var n in options.extraData)
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
.appendTo(form)[0]);
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
$form.attr('action', a);
t ? $form.attr('target', t) : $form.removeAttr('target');
$(extraInputs).remove();
}
}, 10);
function cb() {
if (cbInvoked++) return;
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var operaHack = 0;
var ok = true;
try {
if (timedOut) throw 'timeout';
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
if (doc.body == null && !operaHack && $.browser.opera) {
operaHack = 1;
cbInvoked--;
setTimeout(cb, 100);
return;
}
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header){
var headers = {'content-type': opts.dataType};
return headers[header];
};
if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
xhr.responseText = ta ? ta.value : xhr.responseText;
}
else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, opts.dataType);
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
$(this).ajaxSubmit(options);
return false;
}).each(function() {
$(":submit,input:image", this).bind('click.form-plugin',function(e) {
var form = this.form;
form.clk = this;
if (this.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - this.offsetLeft;
form.clk_y = e.pageY - this.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
});
});
};
$.fn.ajaxFormUnbind = function() {
this.unbind('submit.form-plugin');
return this.each(function() {
$(":submit,input:image", this).unbind('click.form-plugin');
});
};
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
continue;
}
var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle them here
var inputs = form.getElementsByTagName("input");
for(var i=0, max=inputs.length; i < max; i++) {
var input = inputs[i];
var n = input.name;
if(n && !input.disabled && input.type == "image" && form.clk == input)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
$.fn.formSerialize = function(semantic) {
return $.param(this.formToArray(semantic));
};
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
return $.param(a);
};
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
$.fn.resetForm = function() {
return this.each(function() {
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};
$.fn.enable = function(b) {
if (b == undefined) b = true;
return this.each(function() {
this.disabled = !b
});
};
$.fn.selected = function(select) {
if (select == undefined) select = true;
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
function log() {
if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})(jQuery);
</script>

Factory pattern within Angular?

Someone mentioned I should use a true Factory pattern below so I don't have to constantly supply the typeName. How can this be accomplished within JavaScript and Angular. If it were C#, I wouldn't have a problem, but the Java reference / value types and Angular are making my brain hurt.
(function () {
'use strict';
angular
.module('blocks.object-cache');
objectCache.$inject = ['CacheFactory', '$auth'];
function objectCache(CacheFactory, $auth) {
var _options = {
maxAge : (60 * 60 * 1000),
deleteOnExpire : 'passive',
storageMode : 'localStorage'
};
var service = {
setOptions : setOptions,
getCache : getCache,
clear : clear,
getAll : getAll,
getItem : getItem,
getItems : getItems,
putItem : putItem,
putItems : putItems,
getItemsByKey : getItemsByKey,
getItemByKeyFirst : getItemByKeyFirst,
getItemByKeySingle : getItemByKeySingle,
removeItemsByKey : removeItemsByKey,
removeItemByKey : removeItemByKey,
putItemsByKey : putItemsByKey,
putItemByKey : putItemByKey
};
return service;
////////////////////////////////////////////////////////////////////////////////
function setOptions (options) {
options = options || {};
options.maxAge = options.maxAge = _options.maxAge;
options.deleteOnExpire = options.deleteOnExpire = _options.deleteOnExpire;
options.storageMode = options.storageMode = _options.storageMode;
_options = options;
}
function getCache(typeName) {
var cacheName = [getUserId(), normalizeTypeName(typeName || 'objects')].join('_');
var cache = CacheFactory(cacheName);
if (cache) { return cache; }
cache = CacheFactory(cacheName, _options);
return cache;
}
function clear (typeName) {
var cache = getCache(typeName);
cache.removeAll();
return (!cache.keys() || (cache.keys().length < 1));
}
function getAll (typeName) {
var cache = getCache(typeName);
var result = [];
(cache.keys() || []).forEach(function(key){
result.push(cache(key));
});
return result;
}
function getItem(typeName, id) {
if (typeof id == 'undefined' || !id.trim) { return null; }
var cache = getCache(typeName);
return cache.get(id);
}
function getItems(typeName, ids) {
var cache = getCache(typeName),
result = [],
_ids = [];
(ids || []).forEach(function(id){
if (_ids.indexOf(id) < 0) {
_ids.push(id);
var item = cache.get(id);
if (item) { result.push(item); }
}
});
return result;
}
function putItem(typeName, item, id, refresh) {
if (typeof item == 'undefined') { return false; }
if (typeof id == 'undefined' || !id.trim) { return false; }
var cache = getCache(typeName);
var existing = cache.get(id);
if (existing && !refresh) { return true; }
if (existing) { cache.remove(id); }
cache.put(item, id);
return (!!cache.get(id));
}
function putItems(typeName, items, idField, refresh) {
var cache = getCache(typeName);
(items || []).forEach(function(item){
var id = item[idField];
if (typeof id != 'undefined') {
var existing = cache.get(id);
if (existing && !!refresh) { cache.remove(id); }
if (!existing || !!refresh) { cache.put(item, id); }
if (!cache.get(id)) { return false; }
}
});
return true;
}
function getItemsByKey(typeName, key, value, isCaseSensitive) {
var result = [];
(getAll(typeName) || []).forEach(function(item){
var itemValue = item[key];
if (typeof itemValue != 'undefined') {
if ((typeof value == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || value.toLowerCase() == itemValue.toLowerCase())) {
result.push(item);
} else if (((typeof value) == (typeof itemValue)) && (value == itemValue)) {
result.push(item);
} else {
// Other scenarios?
}
}
});
return result;
}
function getItemByKeyFirst(typeName, key, value, isCaseSensitive) {
var items = getItemsByKey(typeName, key, value, isCaseSensitive) || [];
return (items.length > 0) ? items[0] : null;
}
function getItemByKeySingle(typeName, key, value, isCaseSensitive) {
var items = getItemsByKey(typeName, key, value, isCaseSensitive) || [];
return (items.length === 0) ? items[0] : null;
}
function removeItemsByKey (typeName, keyField, values, isCaseSensitive) {
var cache = getCache(typeName),
keysToRemove = [];
(cache.keys() || []).forEach(function(key){
var item = cache.get[key],
itemValue = item[keyField];
if (typeof itemValue != 'undefined') {
for (var v = 0; v < (values || []).length; v += 1) {
if ((typeof values[v] == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || values[v].toLowerCase() == itemValue.toLowerCase())) {
keysToRemove.push(key);
break;
} else if (((typeof values[v]) == (typeof itemValue)) && (values[v] == itemValue)) {
keysToRemove.push(key);
break;
} else {
// Other scenarios?
}
}
}
});
var success = true;
keysToRemove.forEach(function(key){
cache.remove(key);
if (cache.get(key)) { success = false; }
});
return success;
}
function removeItemByKey (typeName, keyField, value, isCaseSensitive) {
return removeItemsByKey(typeName, keyField, [value], isCaseSensitive);
}
function putItemsByKey(typeName, items, keyField, refresh, isCaseSensitive) {
if (!!refresh) {
var values = _.map((items || []), keyField);
if (!removeItemsByKey(typeName, keyField, values, isCaseSensitive)) { return false; }
}
var cache = getCache(typeName);
(items || []).forEach(function(item){
var id = item[keyField];
if (typeof value != 'undefined') { cache.put(item, id); }
if (!cache.get(id)) { return false; }
});
return true;
}
function putItemByKey(typeName, item, keyField, refresh, isCaseSensitive) {
return putItemsByKey(typeName, [item], keyField, refresh, isCaseSensitive);
}
function getUserId () {
return $auth.isAuthenticated() ? ($auth.getPayload().sub || 'unknown') : 'public';
}
function normalizeTypeName (typeName) {
return typeName.split('.').join('-');
}
}
})();
I'm not an Angular guru, but couldn't you just move the functions to achieve a factory-like pattern? I have not tested this, but with about two minutes of copy-n-paste...
Edit: Removed your nested iterate functions.
(function () {
'use strict';
angular
.module('blocks.object-cache')
.service('ObjectCache', ObjectCache);
ObjectCache.$inject = ['CacheFactory', '$auth'];
function ObjectCache(CacheFactory, $auth) {
var _options = {
maxAge : (60 * 60 * 1000),
deleteOnExpire : 'passive',
storageMode : 'localStorage'
};
var factory = {
getCache : getCache
};
return factory;
////////////////////////////
function getCache(typeName, options) {
options = options || {};
options.maxAge = options.maxAge = _options.maxAge;
options.deleteOnExpire = options.deleteOnExpire = _options.deleteOnExpire;
options.storageMode = options.storageMode = _options.storageMode;
typeName = normalizeTypeName(typeName || 'objects');
var userId = getUserId() || 'public';
var name = userId + '_' + typeName;
var service = {
type : typeName,
user : userId,
name : name,
options : options,
cache : CacheFactory(name) || CacheFactory.createCache(name, options),
clear : function () {
this.cache.removeAll();
},
getAll : function () {
var result = [];
var keys = this.cache.keys() || [];
for (var i = 0; i < keys.length; i += 1) {
result.push(this.cache(keys[i]));
}
return result;
},
getItems : function (ids) {
var result = [],
_ids = [];
for (var i = 0; i < (ids || []).length; i += 1) {
var id = ids[i];
if (_ids.indexOf(id) < 0) {
_ids.push(id);
var item = this.cache.get(id);
if (item) { result.push(item); }
}
}
return result;
},
getItem : function (id) {
var items = this.getItems([id]);
return (items.length > 0) ? items[0] : null;
},
putItem : function (item, id, refresh) {
var existing = this.cache.get(id);
if (existing && !refresh) { return true; }
if (existing) { this.cache.remove(id); }
this.cache.put(item, id);
return (!!this.cache.get(id));
},
putItems : function (items, idField, refresh) {
var success = true;
for (var i = 0; i < (items || []).length; i += 1) {
var item = items[i];
var id = item[idField];
if (typeof id != 'undefined') {
if (this.putItem(item, id, refresh)) { success = false; }
}
}
return success;
},
getItemsByKey : function (key, value, isCaseSensitive) {
var result = [];
(this.getAll() || []).forEach(function(item){
var itemValue = item[key];
if (typeof itemValue != 'undefined') {
if ((typeof value == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || value.toLowerCase() == itemValue.toLowerCase())) {
result.push(item);
} else if (((typeof value) == (typeof itemValue)) && (value == itemValue)) {
result.push(item);
} else {
// Other scenarios?
}
}
});
return result;
},
getItemByKeyFirst : function (key, value, isCaseSensitive) {
var items = this.getItemsByKey(key, value, isCaseSensitive) || [];
return (items.length > 0) ? items[0] : null;
},
getItemByKeySingle : function (key, value, isCaseSensitive) {
var items = this.getItemsByKey(key, value, isCaseSensitive) || [];
return (items.length === 0) ? items[0] : null;
},
removeItemsByKey : function (keyField, values, isCaseSensitive) {
var keysToRemove = [],
keys = this.cache.keys() || [];
for (var k = 0; k < keys.length; k += 1) {
var key = keys[k];
var item = this.cache.get(key);
var itemVal = item[keyField];
if (typeof itemVal != 'undefined') {
for (var v = 0; v < (values || []).length; v += 1) {
if ((typeof values[v] == 'string') && (typeof itemVal == 'string') && (!isCaseSensitive || values[v].toLowerCase() == itemVal.toLowerCase())) {
keysToRemove.push(key);
break;
} else if (((typeof values[v]) == (typeof itemVal)) && (values[v] == itemVal)) {
keysToRemove.push(key);
break;
} else {
// Other scenarios?
}
}
}
}
var success = true;
for (var r = 0; r < keysToRemove.length; r += 1) {
this.cache.remove(keysToRemove[r]);
if (this.cache.get(keysToRemove[r])) { success = false; }
}
return success;
},
removeItemByKey : function (keyField, value, isCaseSensitive) {
return this.removeItemsByKey(keyField, [value], isCaseSensitive);
},
putItemsByKey : function(items, keyField, refresh, isCaseSensitive) {
if (!!refresh) {
var values = _.map((items || []), keyField);
if (!this.removeItemsByKey(keyField, values, isCaseSensitive)) { return false; }
}
for (var i = 0; i < (items || []).length; i += 1) {
var id = items[i][keyField];
if (typeof id != 'undefined') {
this.cache.put(items[i], id);
if (!this.cache.get(id)) { return false; }
}
}
return true;
},
putItemByKey : function (item, keyField, refresh, isCaseSensitive) {
return this.putItemsByKey([item], keyField, refresh, isCaseSensitive);
}
};
return service;
}
function getUserId () {
return $auth.isAuthenticated() ? ($auth.getPayload().sub || 'unknown') : null;
}
function normalizeTypeName (typeName) {
return typeName.split('.').join('-');
}
}
})();

Uncaught TypeError: Cannot read property 'options' of null

I cannot figure out why I keep getting this error:
Uncaught TypeError: Cannot read property 'options' of null
getFSREPlist
(anonymous function)
The error is referencing this line of code (21):
document.getElementById(elementidupdate).options.length=0;
What is weird is that it was working prior to this new google map api I just put on. Also, it is pulling the country code "1" and putting it in the drop down, but not the province code "19".
Here is the on page script:
getFSREPlist('1', 'fsrep-search-province', 'CountryID', '19');getFSREPlist('19', 'fsrep-search-city', 'ProvinceID', '3'); request.send(null);
Here is the full file:
function sack(file) {
this.xmlhttp = null;
this.resetData = function () {
this.method = "POST";
this.queryStringSeparator = "?";
this.argumentSeparator = "&";
this.URLString = "";
this.encodeURIString = true;
this.execute = false;
this.element = null;
this.elementObj = null;
this.requestFile = file;
this.vars = new Object();
this.responseStatus = new Array(2);
};
this.resetFunctions = function () {
this.onLoading = function () {};
this.onLoaded = function () {};
this.onInteractive = function () {};
this.onCompletion = function () {};
this.onError = function () {};
this.onFail = function () {};
};
this.reset = function () {
this.resetFunctions();
this.resetData();
};
this.createAJAX = function () {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
if (!this.xmlhttp) {
if (typeof XMLHttpRequest != "undefined") {
this.xmlhttp = new XMLHttpRequest();
} else {
this.failed = true;
}
}
};
this.setVar = function (name, value) {
this.vars[name] = Array(value, false);
};
this.encVar = function (name, value, returnvars) {
if (true == returnvars) {
return Array(encodeURIComponent(name), encodeURIComponent(value));
} else {
this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
}
}
this.processURLString = function (string, encode) {
encoded = encodeURIComponent(this.argumentSeparator);
regexp = new RegExp(this.argumentSeparator + "|" + encoded);
varArray = string.split(regexp);
for (i = 0; i < varArray.length; i++) {
urlVars = varArray[i].split("=");
if (true == encode) {
this.encVar(urlVars[0], urlVars[1]);
} else {
this.setVar(urlVars[0], urlVars[1]);
}
}
}
this.createURLString = function (urlstring) {
if (this.encodeURIString && this.URLString.length) {
this.processURLString(this.URLString, true);
}
if (urlstring) {
if (this.URLString.length) {
this.URLString += this.argumentSeparator + urlstring;
} else {
this.URLString = urlstring;
}
}
this.setVar("rndval", new Date().getTime());
urlstringtemp = new Array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeURIString) {
encoded = this.encVar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = Array(encoded[1], true);
key = encoded[0];
}
urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
}
if (urlstring) {
this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
} else {
this.URLString += urlstringtemp.join(this.argumentSeparator);
}
}
this.runResponse = function () {
eval(this.response);
}
this.runAJAX = function (urlstring) {
if (this.failed) {
this.onFail();
} else {
this.createURLString(urlstring);
if (this.element) {
this.elementObj = document.getElementById(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == "GET") {
totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestFile, true);
try {
this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
} catch (e) {}
}
this.xmlhttp.onreadystatechange = function () {
switch (self.xmlhttp.readyState) {
case 1:
self.onLoading();
break;
case 2:
self.onLoaded();
break;
case 3:
self.onInteractive();
break;
case 4:
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;
if (self.execute) {
self.runResponse();
}
if (self.elementObj) {
elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") {
self.elementObj.value = self.response;
} else {
self.elementObj.innerHTML = self.response;
}
}
if (self.responseStatus[0] == "200") {
self.onCompletion();
} else {
self.onError();
}
self.URLString = "";
break;
}
};
this.xmlhttp.send(this.URLString);
}
}
};
this.reset();
this.createAJAX();
}
var ajax = new Array();
function getFSREPlist(sel, elementidupdate, fsrepvariable, currentvalue) {
if (sel == '[object]' || sel == '[object HTMLSelectElement]') {
var FSREPID = sel.options[sel.selectedIndex].value;
} else {
var FSREPID = sel;
}
document.getElementById(elementidupdate).options.length = 0;
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'http://www.cabcot.com/wp-content/plugins/firestorm-real-estate-plugin/search.php?' + fsrepvariable + '=' + FSREPID + '&cvalue=' + currentvalue;
ajax[index].onCompletion = function () {
ElementUpdate(index, elementidupdate)
};
ajax[index].runAJAX();
}
function ElementUpdate(index, elementidupdate) {
var obj = document.getElementById(elementidupdate);
eval(ajax[index].response);
}
You should call getFSREPlist when DOM is loaded. I ran
document.getElementById('fsrep-search-province').options.length=0
from chrome´s console. while page was still loading and caused that same error.
http://i.imgur.com/GBFizq1.png

Categories