Have searched high an low for an answer without luck.
I am trying to pass a variable between two functions. The first function runs when the page loads, pulling settings from a google script file. I don't have any issues with this part. I am however, struggling with the second function which runs 'on click' and requires some variables from the first function.
Any guidance is appreciated.
<script>
$(function() {
google.script.run
.withSuccessHandler(loadSettings)
.withFailureHandler(showStatus)
.withUserObject($('#button-bar').get())
.getSettings();
function loadSettings(settings) {
$("select").data("option",settings.userInput1);
};
$('#add1').click(function(){
var option0 = $("select").data("option");}
...etc.
})
</script>
I assume settings.userInput1 is a string. Try the below
<script>
var userInput ="";
$(function() {
google.script.run
.withSuccessHandler(loadSettings)
.withFailureHandler(showStatus)
.withUserObject($('#button-bar').get())
.getSettings();
function loadSettings(settings) {
userInput = settings.userInput1;
$("select").data("option",settings.userInput1);
};
$('#add1').click(function(){
//you can now use userInput in this function
var option0 = $("select").data("option");}
...etc.
})
if other solutions are not working then you should go this way -
Make a hidden field
store that variables value in that hidden field
in the next function get the value from that field
$("#hiddenfield_id").val();
Related
I am not a javascript expert at all and expect this to be a fairly simple task.
I am trying to grab the value from a hidden field on my page called pageVariant so I can store it as a value inside of Google Tag Manager. I just don't know how to write the javascript.
This is the code I have tried, but know it is not right. Any help here would be appreciated.
function() {
var capturedText = document.querySelector("#lp-pom-form-162 > form > input[type=hidden]:nth-child(2)");
return capturedText; }
First of all provide a name to your function.
Then use the code mentioned below:
function inputText() {
var capturedText = document.querySelector("input[name='pageVariant']").value;
return capturedText;
}
I want to access one function variable in another function,
My first function and variable
var max;
papaya.viewer.Viewer.prototype.pagination = function () {
var max = this.volume.header.imageDimensions.zDim;
}
My second function
papaya.Container.fillContainerHTML = function(){
// I want to access max value here
}
I want to access the max value to a second function,
I tried many ways to do but I can't able to make it.
Just declare max as a global variable, outside the functions, where it can be accessed by both, like so:
var max;
papaya.viewer.Viewer.prototype.pagination = function () {
max = this.volume.header.imageDimensions.zDim;
}
papaya.Container.fillContainerHTML = function(){
// You can now access max value here
}
If it doesn't work, send an online demo so we can help.
You can return this value and get from fillContainerHTML
papaya.viewer.Viewer.prototype.pagination = function () {
return this.volume.header.imageDimensions.zDim;
}
papaya.Container.fillContainerHTML = function(){
var view = new papaya.viewer.Viewer();
var a = view.pagination();
console.log(a);
}
The Best and easiest solution to your question
Hi. I had researched a lot about the question you are asking. I watched many tutorials, but they were really complicated. So once, I was working on a project. I didn't realise, but I used a variable created/edited in a function in another function. It was really simple. You need to create Local Storage to do this. The localStorage and sessionStorage properties allow to save key/value pairs in a web browser. It is Supported in almost every famous or known web browser like Google Chrome, Firefox, Opera, safari, Microsoft Edge etc.
Note: if you click Run code snippet button, the code won't work because Stack Overflow doesn't support Local Storage. So, go to another text editor like notepad, run the code, and see the result on any Browser (mentioned above). It will work.
// Creates a variable
var max = "Nothing";
function btn1() {
// Makes a change to max variable
var max = "Max variable changed";
// Creates Local Storage on browser
var setLocalStorage = localStorage.setItem("max", max);
}
function btn2() {
var getLocalStorage = localStorage.getItem("max");
document.ById("text").innerHTML = getLocalStorage;
}
<html>
<body>
<p id="text"> Nothing </p>
<button onclick="btn1()"> Make change </button>
<button onclick="btn2()"> See change </button>
</body>
</html>
i am having trouble solving this, i'm trying to load a page which process a variable given by an input form then show the content based on the input, this worked fine, but i am also trying to refresh and update that input every 2 seconds
Below are my codes
<script>
$(document).ready(function(){
function getData(){
$("#dateslot").change(function(){
var inputField= $('#dateslot').val();
$("#timeslot").load('burgerorder_check.php?dateselect='+inputField);
});
setTimeout(getData,1000);
};
getData();
});
</script>
I'm trying to create a function that if someone else picked that, you won't be able to, which i successfully coded but not for the refresh part.
You have the methods and variables in the wrong order. You should probably set a variable outside the getData scope that can change at anytime, then just use that variable when fetching data.
Also, use setInterval if you want to repeat the function. setTimeout is simply a delay.
var val; // the select value is stored here
$("#dateslot").change(function(){
val = $(this).val(); // change the value
}
setInterval(getData,1000);
getData();
function getData(){
if ( val ) {
$("#timeslot").load('burgerorder_check.php?dateselect='+val);
}
}
Instead of re-writing a massive block of code each time, I'm trying to incorporate functions into my work but I'm having trouble making it work.
Basically, I've got a selection of radio buttons and I'm performing some stuff each time a radio button is clicked. (I'm actually loading an iFrame). However, I need to make the iFrame SRC different for each radio button so how would I cater for this within the function?
The function:
jQuery.fn.switchPreview = function () {
$('.liveDemoFrame').remove();
$('.liveDemoHand').append('<iframe class="liveDemoFrame" src="themes/src/' + themeName + '/" width="100%" height="300" scrolling="no"><p>Your browser does not support iframes.</p></iframe>');
$('.liveDemoHand').append('<div class="switchPreview"><div class="loadingPreview"></div></div>');
$('.liveDemoFrame').load(function() {
$('.switchPreview').fadeOut();
$('.switchPreview').remove();
$('.liveDemoFrame').fadeIn();
});
return this;
}
Within the iFrame SRC I have a variable called themeName. I need this to somehow change for each radio button. You can see within the code that calls the function I've tried to declare the variable each time but this still gives me an undefined error.
The code that calls it:
$('#cTheme1').click(function () {
$('input:radio[name=mgChooseTheme]:nth(1)').attr('checked',true);
var themeName = 'theme1';
$('.liveDemoFrame').switchPreview();
});
$('#cTheme2').click(function () {
$('input:radio[name=mgChooseTheme]:nth(2)').attr('checked',true);
var themeName = 'theme2';
$('.liveDemoFrame').switchPreview();
});
$('#cTheme3').click(function () {
$('input:radio[name=mgChooseTheme]:nth(3)').attr('checked',true);
var themeName = 'theme3';
$('.liveDemoFrame').switchPreview();
});
I'm sure this is something very simple but I'm still learning so little things always throw me off!
Pass in the themeName as an argument of the switchPreview function.
-Change the first line of the function to:
jQuery.fn.switchPreview = function (themeName) {
-For each of the three times you are calling the function, make sure you are passing in the argument, i.e:
$('.liveDemoFrame').switchPreview(themeName);
Why not just update the src tag of the iframe ...
$('#cTheme1').click(function () {
$('input:radio[name=mgChooseTheme]:nth(1)').attr('checked',true);
$('#liveDemoFrame').attr('src', <the new url>);
});
Then your iframe would already need to be part of the page :
<iframe id='liveDemoFrame' src='<default page>'></iframe>
i notice your using a CLASS attribute on your iFrame and accessing it using that - you really need to think about using the ID attribute if you are just wanting to refer to a single object. (as in my example above)
I'm fetching a JSON response and with that response, I have two values:
Air shipment cost.
Land shipment cost.
I want to save those two values somewhere in the client so that when a user chooses either 1 radio button or the other, I add that value to another element on the page.
Here's what I'm doing:
<script type="text/javascript">
$(document).ready(function () {
var landCost;
var airCost;
$("#ddlCiudad").change(function () {
var idCity = $("#ddlCiudad").val();
$.getJSON("/ProductCheckout/GetPriceForLocation", { cityId: idCity, productId: idProduct, type: "land" },
function (cityData) {
console.log("Recieved json data."); //This part works. It outputs.
var data = $.parseJSON(cityData);
console.log("Parse JSON response."); //This part works. It outputs.
landCost = data.LandCost;
console.log("Assigned value of LandCost"); //FAILS HERE. nothing is shown. not even an error.
airCost = data.AirCost;
console.log("Assigned value of AirCost");
alert(landCost);
console.log("Alerted land!");
alert(airCost);
console.log("Alerted air!");
}
);
});
So what do you suggest? I need to have the values of this JSON response, available for usage on that page, if I declare the variable inside the change() event, it'll be out of scope.
{"DaysToShip":" TER = 48 Hrs / AER = 24 Hrs","LandCost":"25,00","AirCost":""}
try
landCost = cityData.LandCost;
If you really must use global variables, you can attach them directly to the window object.
window.airCost = cityData.AirCost;
Really though you want to have the json request and the 'radio button' handling in the same scope, so that you're not polluting the global namespace at all.
Your call to $.parseJSON() is returning null because the data passed to your callback has already been parsed to JSON.
var json = {LandCost:3, AirCost:5},
results = $.parseJSON(json);
console.log(results); // results == null
IF you want to globally declare your variables, either put them outside the jQuery closure ($(document).ready(function () {...});), or don't use var to declare them. If you don't use the var keyword the variable will default to a global.
Here is a jsfiddle of setting global variables without using the var keyword: http://jsfiddle.net/jasper/JWtbV/
Have you considered using jQuery's $.data() function to attached the values directly to the body element in the DOM and accessing it from there?
// Set Values
$('body').data('landCost', data.LandCost);
$('body').data('airCost', data.AirCost);
// Retrieve Values //
console.log($('body').data('landCost');
console.log($('body').data('airCost');
Hope it helps.