Understanding callback function differences - javascript

My code:
checkIsMotoOrEcomerce: function(booAnim) {
var objIsEcmOrMto = $('.isMotoOrEcm'),
objEcom = objIsEcmOrMto.filter('[name="ecommerce"]'),
objMoto = objIsEcmOrMto.filter('[name="moto"]'),
objMotoBox = $('.motoBox'),
objEcmBox = $('.apiIntegrationBox'),
strBehaviorShow,
strBehaviorHide,
objMain = this;
if (booAnim) {
strBehaviorShow = 'slideDown';
strBehaviorHide = 'slideUp';
} else {
strBehaviorShow = 'show';
strBehaviorHide = 'hide';
}
if (objEcom.is(':checked')) {
objEcmBox[strBehaviorShow](objMain.checkIsMotoOrEcmVisible());
} else {
objEcmBox[strBehaviorHide](objMain.checkIsMotoOrEcmVisible());
}
if (objMoto.is(':checked')) {
objMotoBox[strBehaviorShow](objMain.checkIsMotoOrEcmVisible());
} else {
objMotoBox[strBehaviorHide](objMain.checkIsMotoOrEcmVisible());
}
},
checkIsMotoOrEcmVisible: function() {
var objMotoBox = $('.motoBox'),
objEcmBox = $('.apiIntegrationBox');
if (objMotoBox.is(':visible') && !objEcmBox.is(':visible')) {
console.log('moto');
} else if (!objMotoBox.is(':visible') && objEcmBox.is(':visible')) {
console.log('eccomerce');
} else if (objMotoBox.is(':visible') && objEcmBox.is(':visible')) {
console.log('both');
} else {
console.log('none');
}
}
I cannot understand why this is working on first run, but when I'm running second time then its returning error "Uncaught TypeError: undefined is not a function".
When I am using this code:
if (objEcom.is(':checked')) {
objEcmBox[strBehaviorShow](objMain.checkIsMotoOrEcmVisible);
} else {
objEcmBox[strBehaviorHide](objMain.checkIsMotoOrEcmVisible);
}
if (objMoto.is(':checked')) {
objMotoBox[strBehaviorShow](objMain.checkIsMotoOrEcmVisible);
} else {
objMotoBox[strBehaviorHide](objMain.checkIsMotoOrEcmVisible);
}
It not returning any errors but working only on first run.
Can you help me understand the differences between using objMain.checkIsMotoOrEcmVisible() and objMain.checkIsMotoOrEcmVisible
Why when I put function name instead calling object propety, everything seams to work?
function blabla() {
var objMotoBox = $('.motoBox'),
objEcmBox = $('.apiIntegrationBox');
if (objMotoBox.is(':visible') && !objEcmBox.is(':visible')) {
console.log('moto');
} else if (!objMotoBox.is(':visible') && objEcmBox.is(':visible')) {
console.log('eccomerce');
} else if (objMotoBox.is(':visible') && objEcmBox.is(':visible')) {
console.log('both');
} else {
console.log('none');
}
}
if (objEcom.is(':checked')) {
objEcmBox[strBehaviorShow](blabla());
} else {
objEcmBox[strBehaviorHide](blabla());
}
if (objMoto.is(':checked')) {
objMotoBox[strBehaviorShow](blabla());
} else {
objMotoBox[strBehaviorHide](blabla());
}

Related

PHP Form Post + JS function

I can't make work together my post code php and my js function.
I have a form to compile, in that form i have a phone number and i wanted to execute php and js functions.
This is my js function to check the phone number field:
<script type="text/javascript">
var link = <?php echo json_encode($pagamento_link); ?>;
$('#acquistato').click(function() {
if (!phoneCheck(document.getElementById("privato_telefono"))) {
$('#errore_tel').removeAttr("style");
$('#errore_trovato').removeAttr("style");
return false;
} else {
console.log("done");
window.location.href = link;
return false;
}
})
And this is my post form php:
if ($_POST && isset($_POST['privacy'])) {
$ordine = KronosOrdine::initID($_SESSION['carrello']);
$ordine->set('email', $_POST['privato_email'])->save();
$ordine
->set('nome_fatt', $_POST['privato_nome'])
->set('cognome_fatt', $_POST['privato_cognome'])
->set('codice_fiscale', $_POST['privato_codice_fiscale'])
->set('nazione_fatt', $_POST['privato_stato'])
->set('provincia_fatt', $_POST['privato_provincia'])
->set('paese_fatt', $_POST['privato_citta'])
->set('cap_ordine_fatt', $_POST['privato_cap'])
->set('indirizzo_fatt', $_POST['privato_indirizzo'])
->save();
if (isset($_POST['flag_azienda'])) {
$ordine
->set('is_azienda', 1)
->set('ragioneSociale', $_POST['ragione_sociale'])
->set('partita_iva', $_POST['azienda_partita_iva'])
->set('sdi', $_POST['azienda_sdi'])
->save();
} else {
$ordine->set('is_azienda', 0)->save();
}
if (isset($_POST['form-condition-1'])) {
$nome_sped = $_POST['form-condition-2'];
$cognome_sped = $_POST['form-condition-3'];
$nazione_sped = $_POST['form-condition-5'];
$provincia_sped = $_POST['form-condition-6'];
$paese_sped = $_POST['form-condition-7'];
$cap_ordine_sped = $_POST['form-condition-8'];
$indirizzo_sped = $_POST['form-condition-4'];
$ordine->set('note', $_POST['form-condition-9'])->save();
} else {
$nome_sped = $_POST['privato_nome'];
$cognome_sped = $_POST['privato_cognome'];
$nazione_sped = $_POST['privato_stato'];
$provincia_sped = $_POST['privato_provincia'];
$paese_sped = $_POST['privato_citta'];
$cap_ordine_sped = $_POST['privato_cap'];
$indirizzo_sped = $_POST['privato_indirizzo'];
}
$ordine
->set('nome_sped', $nome_sped)
->set('cognome_sped', $cognome_sped)
->set('nazione_sped', $nazione_sped)
->set('provincia_sped', $provincia_sped)
->set('paese_sped', $paese_sped)
->set('cap_ordine_sped', $cap_ordine_sped)
->set('indirizzo_sped', $indirizzo_sped)
->save();
if (isset($_SESSION['utente'])) {
$utente = KronosUtente::initID($_SESSION['utente']);
$utente
->set('nome', $_POST['privato_nome'])
->set('cognome', $_POST['privato_cognome'])
->set('telefono', $_POST['privato_telefono'])
->set('codiceFiscale', $_POST['privato_codice_fiscale'])
->set('stato', $_POST['privato_stato'])
->set('provincia', $_POST['privato_provincia'])
->set('comune', $_POST['privato_citta'])
->set('CAP', $_POST['privato_cap'])
->set('indirizzo', $_POST['privato_indirizzo'])
->save();
if (isset($_POST['form-condition-1'])) {
$utente
->set('stato_sped', $nazione_sped)
->set('provincia_sped', $provincia_sped)
->set('comune_sped', $paese_sped)
->set('CAP_sped', $cap_ordine_sped)
->set('indirizzo_sped', $indirizzo_sped)
->save();
}
if (isset($_POST['flag_azienda'])) {
$utente
->set('is_azienda', 1)
->set('ragioneSociale', $_POST['ragione_sociale'])
->set('partitaIVA', $_POST['azienda_partita_iva'])
->set('sdi', $_POST['azienda_sdi'])
->save();
} else {
$utente
->set('is_azienda', 0)
->save();
}
}
if ($_POST['metodo_pagamento'] == 'bonifico') {
$pagamento_link = "/pagamento/bonifico";
} else {
$pagamento_link = "/pagamento/paypal";
}
}
My problem is that when i submit my form, it only run js code and don't pass through this form post
Can you help me please? Thannks

returning values as a js dictionary, some values are not defined?

I am trying to return multiple variables from a JS function, so I put the variables needed to be returned in a dictionary but when I call they variables later they do not exist?
function event_listeners(){
// Event Listners
$("#add_calculation_button").on('click', function()
{
save_calculation();
});
$("#owned_acres").on('input',function()
{
$("#result_acres_numerator").text( $(this).val());
calculate_NRI();
});
$("#total_acres").on('input',function()
{
$("#result_acres_denominator").text( $(this).val());
calculate_NRI();
});
$("#cross_unit_factor").on('change',function()
{
if(typeof(was_previously_invalid) == "undefined")
{
was_previously_invalid = false
}
if(was_previously_invalid == false)
{
$(this).removeClass("is-invalid");
}
$("#result_cross_unit").text(display($(this).val()));
cross_unit = convert($(this).val())
was_previously_invalid = false
calculate_NRI();
});
$("#ownership_factor").on('change',function()
{
if(typeof(was_previously_invalid) == "undefined")
{
was_previously_invalid = false
}
if(was_previously_invalid == false)
{
$(this).removeClass("is-invalid");
}
$("#result_ownership").text(display($(this).val()));
ownership = convert($(this).val())
was_previously_invalid = false
calculate_NRI();
});
$("#royalty_rate").on('change',function()
{
if(typeof(was_previously_invalid) == "undefined")
{
was_previously_invalid = false
}
if(was_previously_invalid == false)
{
$(this).removeClass("is-invalid");
}
$("#result_royalty_rate").text(display($(this).val()));
royalty = convert($(this).val())
console.log(royalty)
was_previously_invalid = false
calculate_NRI();
});
$("#decimal").on('change',function() {});
$("#percentage").on('change',function() {});
$("#cross_unit_yes").on('change',function()
{
$("#cross_unit_entry_box").show();
$("#cross_unit_results_box").show();
calculate_NRI();
});
$("#cross_unit_no").on('change',function()
{
$("#cross_unit_entry_box").hide();
$("#cross_unit_results_box").hide();
$("#result_cross_unit").text(1);
$("#cross_unit_factor").val(1);
calculate_NRI();
});
$("#show_total_yes").on('change',function()
{
$("#total_history_box").show();
$("#total_history_box").addClass("d-flex");
});
$("#show_total_no").on('change',function()
{
$("#total_history_box").hide();
$("#total_history_box").removeClass("d-flex");
});
$("#divide_out_yes").on('change',function() {alert("Yes!");});
$("#divide_out_no").on('change',function() {alert("No!");});
$("#brp_royalty_rate").on('change',function() {alert("BRP Royalty Rate");});
$("#coval_royalty_rate").on('change',function() {alert("Coval Royalty Rate");});
var dictionary_of_converted_nums = {
Royalty: royalty,
Cross_Unit: cross_unit,
Ownership: ownership,
};
return dictionary_of_converted_nums;
}
then when I try to call each individual return variables
listeners = event_listeners();
try
{
cross_unit_factor = parseFloat(listeners.Cross_Unit).text();
}
catch(err)
{
cross_unit_factor = 1;
}
the results should let the cross_unit_factor be the Cross_Unit variable in the return statement. but all I am getting is a 1 because of the catch error

How make checkbox being true/false just after you checked them

I'm making a "What language you should learn"site but more complex
I don't know why but when i check my checkbox,they don't became true but when i reload the page now they are true
if (document.getElementById("langage1").checked) {
html = true;
}
if (document.getElementById("langage2").checked) {
phpmysql = true;
}
if (document.getElementById("langage3").checked) {
js = true;
}
if (document.getElementById("langage4").checked) {
python = true;
}
if (document.getElementById("langage5").checked) {
java = true;
}
if (document.getElementById("langage6").checked) {
swift = true;
}
if (document.getElementById("langage7").checked) {
batch = true;
}
if (document.getElementById("langage8").checked) {
jquery = true;
}
if (document.getElementById("langage9").checked) {
c = true;
}
if (document.getElementById("langage10").checked) {
cplus = true;
}
if (document.getElementById("langage11").checked) {
objectivec = true;
}
if (document.getElementById("langage12").checked) {
cdiaise = true;
}
if (document.getElementById("langage13").checked) {
construct = true;
}
if (document.getElementById("langage14").checked) {
wordpress = true;
}
if (document.getElementById("langage15").checked) {
unity = true;
}
if (document.getElementById("langage16").checked) {
gamemaker = true;
}
if (document.getElementById("langage17").checked) {
unreal = true;
}
if (document.getElementById("langage1").checked === false) {
html = false;
}
if (document.getElementById("langage2").checked === false) {
phpmysql = false;
}
Here is an example of the commands that should make them true,any idea how to fix that?
You have to add eventlisteners
document.getElementById("langage1").addEventListener("click", myFunction);
// example function
function myFunction() {
document.getElementById("langage1").innerHTML = "YOU CLICKED ME!";
}
This way you tell javascript to fire when you do something, in this chase a click. So every time you click the checkbox myFunction() fires

Unobtrusive date compare validator

So I've been following this tutorial here and it shows you how to validate dates compared with each other. I'm getting an error in the first block of code which I've commented and it says "Unable to get property 'element' of undefined or null reference" which originates from this line of code customValidation.formValidator = $(event.data.source).closest('form').data('validator') does anyone know of a work around for this so I don't get an error. I'm using the latest unobtrusive validation
window.customValidation = window.customValidation ||
{
relatedControlValidationCalled: function (event) {
if (!customValidation.activeValidator) {
customValidation.formValidator = $(event.data.source).closest('form').data('validator');
}
// code error below
customValidation.formValidator.element($(event.data.target));
},
relatedControlCollection: [],
formValidator: undefined,
addDependatControlValidaitonHandler: function (element, dependentPropertyName) {
var id = $(element).attr('id');
if ($.inArray(id, customValidation.relatedControlCollection) < 0) {
customValidation.relatedControlCollection.push(id);
$(element).on(
'blur',
{ source: $(element), target: $('#' + dependentPropertyName) },
customValidation.relatedControlValidationCalled);
}
}
};
adapter:
$.validator.unobtrusive.adapters.add('comparedates', ['otherpropertyname', 'allowequality'],
function (options) {
options.rules['comparedates'] = options.params;
if (options.message) {
options.messages['comparedates'] = options.message;
}
}
);
validator method:
$.validator.addMethod('comparedates', function (value, element, params) {
var otherFieldValue = $('input[name="' + params.otherpropertyname + '"]').val();
if (otherFieldValue && value) {
var currentValue = Date.parse(value);
var otherValue = Date.parse(otherFieldValue);
if ($(element).attr('name').toLowerCase().indexOf('begin') >= 0) {
if (params.allowequality) {
if (currentValue > otherValue) {
return false;
}
} else {
if (currentValue >= otherValue) {
return false;
}
}
} else {
if (params.allowequality) {
if (currentValue < otherValue) {
return false;
}
} else {
if (currentValue <= otherValue) {
return false;
}
}
}
}
customValidation.addDependatControlValidaitonHandler(element, params.otherpropertyname);
return true;
}, '');
Maybe you are loading this code too early, before the form is in the DOM. Make sure your code is protected by $(document).ready(your code here);

can anybody help me how to deal this 2 javascript conflict

The First Script that allows me to create a moving clouds and loop after if reaches the end
// dvdp - volll - iphone alert
var agent=navigator.userAgent.toLowerCase();
var is_iphone = (agent.indexOf('iphone')!=-1);
// TJP - volll
var stispace=new Array();
var jumpspace=new Array();
var skyspace=new Array; skyspace['dir']=-1; skyspace['place']=0;
var smokespace=0;
var shipspace=0;
var cloudspace=new Array();
var stagespace=2000;
cloudspace[1]=new Array(); cloudspace[1]['w']=219; cloudspace[1]['p']=2000;
cloudspace[2]=new Array(); cloudspace[2]['w']=128; cloudspace[2]['p']=1050;
cloudspace[3]=new Array(); cloudspace[3]['w']=51; cloudspace[3]['p']=1200;
cloudspace[4]=new Array(); cloudspace[4]['w']=112; cloudspace[4]['p']=120;
cloudspace[5]=new Array(); cloudspace[5]['w']=219; cloudspace[5]['p']=130;
cloudspace[6]=new Array(); cloudspace[6]['w']=219; cloudspace[6]['p']=1020;
cloudspace[7]=new Array(); cloudspace[7]['w']=219; cloudspace[7]['p']=1400;
var movespace='';
var scrollspace=0;
function $(id) {
return document.getElementById(id);
}
function smoothto(whereto) {
wheretoreal=whereto;
if(scrollspace == 1) {return false;}
if(whereto == 'section_about_who') { whereto='section_about';}
if(whereto == 'section_about_contact') { whereto='section_about';}
scrollspace=1;
wheretoscroll=0;
wherefromscroll=topget();
for(smt=0;smt<pag_sections_name.length;smt++) {
if(smt>0) {wheretoscroll+=pag_sections_height[smt-1]}
if(pag_sections_name[smt] == whereto) {smt=pag_sections_name.length;}
}
if(wherefromscroll==wheretoscroll) {
scrollspace=0;
window.location='#'+wheretoreal;
return false;
}else{
window.paused=1;
clearInterval(int_TJPfloat);
clearInterval(int_TJProllsky);
}
$('vollltv').style.height='0';
tmp=new Array();
steps=20;
for(smt=1;smt<=steps;smt++) {
pt=smt/steps;
if(pt == .5) {
multi=1.5
} else {
multi=(Math.sqrt(Math.abs(2*pt-1))*(2*pt-1)/Math.abs(2*pt-1)+1)/2;
}
multi=Math.sqrt(smt/steps);
tmp[smt]='window.scroll(0,'+(wherefromscroll+(wheretoscroll-wherefromscroll)*multi)+');';
}
tmp[steps]+="window.location='#"+wheretoreal+"';$('vollltv').style.height='278px'; scrollspace=0;";
tmp[steps]+=" window.int_TJProllsky=undefined; window.int_TJProllsky=setInterval('TJProllsky();',200);";
tmp[steps]+="window.int_TJPfloat=undefined; window.int_TJPfloat=setInterval('TJPfloat();',50);";
tmp[steps]+="window.paused=0; ";
//alert(tmp.join("\n"));
ttt=Math.random();
stispace[ttt]=tmp;
setTI(ttt,10);
return false;
}
function volllresize() {
d=document.body.clientWidth;
if(d && d>1000) {
stagespace=d;
}
if($('inter4')) {
if (self.innerHeight) {
ch = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight) {
ch = document.documentElement.clientHeight;
}
else if (document.body) {
ch = document.body.clientHeight;
}
if(ch>600) {
$('inter4').style.height=(ch-534)+'px';
}
}
}
function volllinit(section) {
if(section == 'inter0' && !is_iphone) {
volllresize();
window.onresize=volllresize;
for(i=1;i<cloudspace.length;i++) {
cloudspace[i]['p']*=d/1000;
}
//if(tmp.split('#')[1] == '' || tmp.split('#')[1] == 'section_main') {
// setTimeout('scroll(0,200);',100);
//}
}
else if(section == 'about') {
window.int_TJPfloat=setInterval("TJPfloat();",50);
tmp=location.href+'#';
}
}
window.paused=0;
function TJPmovecloud(cid,pos) {
if(pos > stagespace && window.paused>0 ) {
return;
}
if(pos+cloudspace[cid]['w']>stagespace) {
$('s_cloud'+cid).style.width=stagespace-pos+'px';
} else {
$('s_cloud'+cid).style.width=cloudspace[cid]['w']+'px';
}
$('s_cloud'+cid).style.left=pos+'px';
}
function TJPfloat() {
sy=Math.floor(Math.sin(smokespace)*20+20);
sy2=Math.floor(Math.sin(smokespace)*10+10);
sx=Math.floor(Math.cos(smokespace)*3+3);
//if(smokespace==0) {alert('about.css-be belerakni:'+sy+'px 0 0 '+sx+'px');}
$('g_wave1').style.margin=sy+'px 0 0 '+sy+'px';
$('g_wave2').style.margin=sy2+'px 0 0 '+sy2+'px';
smokespace+=.05; if(smokespace>2*Math.PI) {smokespace-=2*Math.PI;}
if($('inter1')) {
for(i=1;i<cloudspace.length;i++) {
if(cloudspace[i]['p'] >= stagespace) {cloudspace[i]['p']=-cloudspace[i]['w'];}
else if(cloudspace[i]['p'] <= -cloudspace[i]['w']) {cloudspace[i]['p']=stagespace;}
cloudspace[i]['p']-=1+cloudspace[i]['w']/200;
TJPmovecloud(i,cloudspace[i]['p']);
}
}
}
The Second script is the one that creates the bouncing effect like the one on tim van damme
<script type="text/javascript" charset="utf-8">
$('.navigation').each(function () {
var $links = $(this).find('a'),
panelIds = $links.map(function() { return this.hash; }).get().join(","),
$panels = $(panelIds),
$panelwrapper = $panels.filter(':first').parent(),
delay = 500,
heightOffset = 40; // we could add margin-top + margin-bottom + padding-top + padding-bottom of $panelwrapper
$panels.hide();
$links.click(function () {
var link = this,
$link = $(this);
// ignore if already visible
if ($link.is('.selected')) {
return false;
}
$links.removeClass('selected');
$link.addClass('selected');
document.title = 'jQuery look: Tim Van Damme - ' + $link.text();
if ($.support.opacity) {
$panels.stop().animate({opacity: 0 }, delay);
}
$panelwrapper.stop().animate({
height: 0
}, delay, function () {
var height = $panels.hide().filter(link.hash).css('opacity', 1).show().height() + heightOffset;
$panelwrapper.animate({
height: height
}, delay);
});
});
$links.filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':first').click();
});
</script>
This is the error I received
TypeError: Result of expression '$('.navigation')' [null] is not an object. Can anybody please explain to me why this error occur?
You receive this error because if the following function in the first code:
function $(id) {
return document.getElementById(id);
}
This overlaps with jQuery's $ function which is required by the second piece of code. rewrite the first piece of code to use jQuery's $() function or rename $() in the first piece of code and find/replace.
Do you have html elements with the class name "navigation" in your code?

Categories

Resources