How to use variable in function after load PHP file in jQuery? - javascript

How to use variable "hotel" after load step-02.php file?
$(function () {
var hotel = [];
$('#forPrice').on('click', function() {
$('select').each(function() {
if($(this).val() > 0 && $(this).val() < 10) {
var room = {};
room["room"] = $(this).attr('room');
room["price"] = $(this).attr('price');
room["val"] = $(this).val();
room["html"] = $(this).parents(".selectRowRoom").html();
hotel.push(room);
}
});
console.log(hotel);
});
$('#forPrice').click(function () {
$('#Step-01').hide();
$('#Step-02').show();
$('.hiddenAndShow').hide();
$( "#Step-02" ).load( 'step_02.php' );
});
})
I need
room["html"] = $(this).parents(".selectRowRoom").html();
to show after loading step-02.php.
step-02.php:
<div class="thisRoom">
// Insert room["html"] = $(this).parents(".selectRowRoom").html();
</div>

jQuery load() is a shortcut for $.ajax, which is asynchronous, you have to wait for the result to be able to access it.
Luckily load() has a callback that fires when the content is inserted and ready for accessing
$(function() {
var hotel = [];
$('#forPrice').on('click', function() {
$('select').each(function() {
if ($(this).val() > 0 && $(this).val() < 10) {
var room = {};
room["room"] = $(this).attr('room');
room["price"] = $(this).attr('price');
room["val"] = $(this).val();
room["html"] = $(this).parents(".selectRowRoom").html();
hotel.push(room);
}
});
console.log(hotel);
});
$('#forPrice').click(function() {
$('#Step-01').hide();
$('#Step-02').show();
$('.hiddenAndShow').hide();
$("#Step-02").load('step_02.php', function() { // callback here
$("#Step-02").find('.thisRoom').html(JSON.stringify(hotel));
});
});
});

Make hotel global and save key number of room in data attr. Like this :
$(function () {
window.hotel = []; // new
$('#forPrice').on('click', function() {
$('select').each(function() {
if($(this).val() > 0 && $(this).val() < 10) {
var room = {};
room["room"] = $(this).attr('room');
room["price"] = $(this).attr('price');
room["val"] = $(this).val();
room["html"] = $(this).parents(".selectRowRoom").html();
$(this).data("numRoom", hotel.length); // new
hotel.push(room);
}
});
console.log(hotel);
});
$('#forPrice').click(function () {
$('#Step-01').hide();
$('#Step-02').show();
$('.hiddenAndShow').hide();
$( "#Step-02" ).load( 'step_02' );
});
})
//After :
hotel[$(this).data("numRoom")]["html"] = $(this).parents(".selectRowRoom").html();

Related

Using javascript like a function with button

I want to use this code as a function () to be run only when I click a button and not automatically when dropdown is changed. When click on <button onclick="CalendarFilter">Cercar</button> it runs the function. I tried putting the code into this but not working.
function myFunction()
{
CODE HERE
}
$(document).ready(function () {
$('.filter').change(function () {
var values = [];
$('.filter').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push( {
text: $(this).text(),
colId : colIdx
});
});
});
filter('table > tbody > tr', values);
});
function filter(selector, values) {console.log(values);
$(selector).each(function () {
var sel = $(this);
var tokens = sel.text().trim().split('\n');
var toknesObj = [], i;
for(i=0;i<tokens.length;i++){
toknesObj[i] = {
text:tokens[i].trim(),
found:false
};
}
var show = false;
//console.log(toknesObj);
$.each(values, function (i, val) {
if (toknesObj[val.colId].text.search(new RegExp("\\b"+val.text+"\\b")) >= 0) {
toknesObj[val.colId].found = true;
}
});
console.log(toknesObj);
var count = 0;
$.each(toknesObj, function (i, val) {
if (val.found){
count+=1;
}
});
show = (count === values.length);
show ? sel.show() : sel.hide();
});
}
});
When click on Cercar it runs the CalendarFilter
Thanks.
I need a way to run this like this:
function myFunction()
{
$(document).ready(function () {
$('.filter').change(function () {
var values = [];
$('.filter').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push( {
text: $(this).text(),
colId : colIdx
});
});
});
filter('table > tbody > tr', values);
});
function filter(selector, values) {console.log(values);
$(selector).each(function () {
var sel = $(this);
var tokens = sel.text().trim().split('\n');
var toknesObj = [], i;
for(i=0;i<tokens.length;i++){
toknesObj[i] = {
text:tokens[i].trim(),
found:false
};
}
var show = false;
//console.log(toknesObj);
$.each(values, function (i, val) {
if (toknesObj[val.colId].text.search(new RegExp("\\b"+val.text+"\\b")) >= 0) {
toknesObj[val.colId].found = true;
}
});
console.log(toknesObj);
var count = 0;
$.each(toknesObj, function (i, val) {
if (val.found){
count+=1;
}
});
show = (count === values.length);
show ? sel.show() : sel.hide();
});
}
});
}
To call that function using a button.
<button onclick="myFunction()">Cercar</button>
The problem is that this way is not working.
Thanks.

After first click of radio button can not fire change event

My jquery change event of radio button not working after first click and does not give any error please help me. i stuck in this from last week.and also cant count proper value because of this problem.
$('input[name="emailing"]').change(function()
{
checkValue();
});
function checkValue(evt) {
alert('hi');
var package = $("#package_value").val();
var emailing = $('input[name="emailing"]:checked').val();
$('input[name="emailing"]').on("mousedown", function() {
var select = $('input[name="emailing"]:checked').val();
$("#selected").val(select);
}).on("mouseup", function() {
$('input[name="emailing"]').prop('checked', false);
$(this).prop('checked', true).checkboxradio("refresh");
});
var selected = $("#selected").val();
alert(selected);
var update = $("#update").val();
if(update != '')
{
var hiddenPackage = $("#hidden_pricing").val();
var hiddenRadion = $("#hidden_radio").val();
var totalValue = package - hiddenRadion;
if(emailing == 1)
{
$("#package_value").val('');
var value = Number(totalValue) + 38;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 2)
{
$("#package_value").val('');
var value = Number(totalValue) + 55;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 0)
{
$("#package_value").val('');
var value = Number(totalValue) + 0;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
}
}
You should use delegate
$(document).delegate( "input[name='emailing']", "change", function() {
checkValue();
});
Use on() function with any element id instead of (document)
$(document).on('change', 'input[name="emailing"]', function() {
checkValue();
});

insert a function inside an event jquery

i'm trying to insert a function inside this jquery event. This is the event
$(":checkbox").on('change', function() {
$.fn.myFunction();
})
and this is myFunction
$.fn.myFunction = function() {
alert('ciao');
if ($(this).is(':checked')) {
InputInserireInput = $(this).parent().parent().parent().find('.inserirePrezzoDiv');
$(this).closest('div').parent().parent().find('select').prop('value','0');
$(this).find('button').css('background-color','#c31432')
var checkbox = $(this);
InputInserireInput.removeClass('hidden');
var checkboxSelected = $(this).attr('id');
var nomeServizio = ($(this).next('label').text());
$(this).closest('div').parent().parent().find('.titoloPiega').css('color', 'black')
$(this).closest('div').parent().parent().find('button').css('margin-top', -50)
var titleLabel = $(this).closest('div');
var titleSelect = $(titleLabel).parent().parent().find('.titoloPiega');
var option1 = $(titleLabel).parent().parent().find('.option1');
var option2 = $(titleLabel).parent().parent().find('.option2');
var selectOption = ($(titleLabel).parent().parent().find('select'));
var selectOptionID = ($(titleLabel).parent().parent().find('select').attr('id'));
$(selectOption).on('change', function () {
var selectedOption = $(selectOption).prop('value');
if (selectedOption == 1 && checkbox.is(':checked')) {
InputInserireInput.addClass('hidden');
option2.addClass('hidden');
option1.removeClass('hidden');
}
if (selectedOption == 2 && checkbox.is(':checked')) {
InputInserireInput.addClass('hidden');
option1.removeClass('hidden');
option2.removeClass('hidden');
}
if (selectedOption == 0 && checkbox.is(':checked')) {
InputInserireInput.removeClass('hidden');
option1.addClass('hidden');
option2.addClass('hidden');
}
});
} else {
$('.inserirePrezzoDiv').addClass('hidden');
$(this).closest('div').parent().parent().find('.titoloPiega').css('color', '#a5a6a7');
$(this).closest('div').parent().parent().find('select').prop('value','0');
$(this).closest('div').parent().parent().find('.option1').addClass('hidden');
$(this).closest('div').parent().parent().find('.option2').addClass('hidden');
$('.bottoneCss6').css('margin-bottom', 0)
}
};
The first allert work but then all the if statement i thik doesn' match with the event declared before the function. Can anyone help me?
try by replacing :
$(":checkbox").on('change', function() {
$(this).myFunction()
})
you will pass the this (current checkbox) scope to myFunction

detect when 2 calendar values changed

I am making a financial report where user choose 2 dates search_date1 and search_date2, and then a monthly report is generated.
I created first a daily report with only one calendar and when it is changed I apply some AJAX script to it and it works correctly:
var myApp = {};
myApp.search_date = "";
document.getElementById('search_date').onchange = function (e) {
if (this.value != myApp.search_date) {
var d = $("#search_date").val();
$.ajax({
...
});
}
}
Now I can't know how to detect if both calendars are changed to apply AJAX script according to their values.
EDIT
Is it correct to do the following:
var myApp = {};
myApp.search_date1 = "";
myApp.search_date2 = "";
document.getElementById('search_date1').onchange = function (e) {
if (this.value != myApp.search_date1) {
var d1 = $("#search_date1").val();
document.getElementById('search_date2').onchange = function (e) {
if (this.value != myApp.search_date2) {
var d2 = $("#search_date2").val();
$.ajax({
...
})
}
});
}
});
try this:
var temp = {
from: null,
to: null
}
document.getElementById('from').onchange = function(e){
temp.from = e.target.value;
goAjax();
}
document.getElementById('to').onchange = function(e){
temp.to = e.target.value;
goAjax();
}
function goAjax(){
if(temp.from && temp.to && new Date(temp.from) < new Date(temp.to)){
//do ajax call
console.log('valid')
}
}
<input type="date" id='from'/>
<br>
<input type="date" id='to'/>
I would have captured the change event for both elements :
$("#search_date1, #search_date2").on('change',function(){
var d1 = $("#search_date1").val();
var d2 = $("#search_date2").val();
$.ajax({...});
});
What you do in your edit may work, but it would be better (and easier) do something like this
var myApp = {};
myApp.original_search_date1 = $("#search_date1").val();
myApp.original_search_date2 = $("#search_date2").val();
myApp.search_date1 = $("#search_date1").val();
myApp.search_date2 = $("#search_date2").val();
document.getElementById('search_date1').onchange = function (e) {
if ($("#search_date1").val() != myApp.search_date1) {
myApp.search_date1 = $("#search_date1").val();
sendAjax();
}
});
document.getElementById('search_date2').onchange = function (e) {
if ($("#search_date2").val() != myApp.search_date2) {
myApp.search_date2 = $("#search_date2").val();
sendAjax();
}
});
function sendAjax() {
if (myApp.original_search_date1 !== myApp.search_date1 &&
myApp.original_search_date2 !== myApp.search_date2) {
$.ajax({
...
});
}
}
Cant you just set a variable to check if its been changed with true/false then run the script if both variables are true.
Something like,
var searchOneToggled = false,
searchTwoToggled = false;
$('#search_date_one').on('input', function() {
searchOneToggled = true;
runYourFunction();
});
$('#search_date_two').on('input', function() {
searchTwoToggled = true;
runYourFunction();
});
function runYourFunction() {
if(searchOneToggled === true && searchTwoToggled === true) {
alert('hello world');
}
}

JQuery: How to refactor JQuery interaction with interface?

The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )

Categories

Resources