How to pass varaiable in HTML functions through jquery - html

this is my html code. group.participants is an array.
result +=`<button class="gsb-${group.id}" onclick="demo(${group.participants})">`+"DEMO"+`</button><br/>`;
this is my simple javascript code to display the array from the parameter
function demo(participants){
alert(participants);
}
this shows me the error
Uncaught SyntaxError: Unexpected end of input
may I know what is the problem

With Jquery you can use the following to pass data to a selector
$(`.gsb-${group.id}`).data(group.participants);
to recover it you just have to call data() method
$(`.gsb-${group.id}`).data();
Finally like each group have different participants, you will have to append first the group button before add the data to it
result.append(`<button class="gsb-${group.id}" onclick="demo(${group.id})">`+"DEMO"+`</button><br/>`);
$(`.gsb-${group.id}`).data(group.participants);
function demo(groupId) {
var participants = $(`.gsb-${groupId}`).data();
console.log(participants);
}
var result = $('#result');
var group = {
id:1,
participants:[
{name:'test1'},
{name:'test2'}
]
}
result.append(`<button class="gsb-${group.id}" onclick="demo(${group.id})">`+"DEMO"+`</button><br/>`);
$(`.gsb-${group.id}`).data(group.participants);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>

Related

How to create resuable showModalDialog() in Google App Script?

I have ModalDialog that prompts for user date range selection in order to generate the appropriate info. I have several menu items that uses the same prompt so I want to reuse the ModalDialog.
// Available method
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Options for Menu Item N');
// What I hope is available
SpreadsheetApp.getUI().showModalDialog(htmlOutput, 'Options for Menu Item N', userdataN); // pseudocode
// inside HTML
var userdata = Script.host.environment // pseudocode do something with userdata in HTML
However, the showModalDialog() function does not allow me to pass any user data to the html so I have no way to identify which menu item I need to return the user selection to.
How can I create a reusable ModelDialog in this case?
EDIT:
I realized I can write the environment variable value in a sheet and then later from the HTML retrieve the value, but is there a cleaner way to do it?
You could either pass the user data object as a property of the HtmlTemplate object and use scriptlet syntax (see this answer) or do string interpolation. Personally, I prefer the latter option over using Google's built-in template engine. It's slower but much more flexible.
Suppose we have an HTML page called 'app' in the script editor
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>{{global.app}}</h1>
<div id=container>
<ul>
<li>{{name}}</li>
<li>{{email}}</li>
<li>{{age}}</li>
</ul>
Created by {{global.author}}.
</div>
</body>
</html>
You can call HtmlService methods to serve the template as a string.
//serve HTML template as a string
function getTemplateAsString(filename) {
return HtmlService.createTemplateFromFile(filename).getRawContent();
}
You can then pass the html string to the interpolation function:
var config = {
app: "My app",
author: "me"
};
function interpolateString(htmlString, params) {
//Add global variables to the template
for (var configKey in config) {
if (config.hasOwnProperty(configKey)) {
htmlString = htmlString.replace("{{global." + configKey + "}}", config[configKey]);
}
}
//Insert page-specific parameters
for (var paramsKey in params) {
if (params.hasOwnProperty(paramsKey)) {
htmlString = htmlString.replace("{{" + paramsKey + "}}", params[paramsKey]);
}
}
return htmlString;
}
For the last step, you create the HtmlTemplate object from the resulting string and call the 'evaluate()' method on it. Calling evaluate returns a valid HtmlOutput object instance that you can pass to UI methods
var template = HtmlService.createTemplate(htmlString);
ui.showModalDialog(template.evaluate(), "My dialog");

Error with custom Search and Replace function for Google Sites

I'm trying to use a script to replace a particular string with a different string. I think the code is right, but I keep getting the error "Object does not allow properties to be added or changed."
Does anyone know what could be going wrong?
function searchAndReplace() {
var teams = SitesApp.getPageByUrl("https://sites.google.com/a/directory/teams");
var list = teams.getChildren();
list.forEach(function(element){
page = element.getChildren();
});
page.forEach(function(element) {
var html = element.getHtmlContent();
html.replace(/foo/, 'bar');
element.setHtmlContent = html;
});
};
Try This:
Javascript reference:
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
I think the issue here is that forEach cannot change the array that it is called upon. From developer.mozilla.org "forEach() does not mutate the array on which it is called (although callback, if invoked, may do so)."
Try doing it with a regular loop.

Knockout binding from a JSON data string

I'm currently using Knockout to render my HTML page, but I'm stuck when I'm trying to render my HTML when the data is stored in a simple JSON file.
The Json file is here:
{
"name": "Office Web Controls 2014"
}
Here's the function to load my Json string:
<script type="text/javascript">
function AppViewModel() {
this.data = { };
$.getJSON("Resources/Data/Ribbon.json", function(retrievedData) {
this.data = ko.mapping.fromJSON(retrievedData);
console.log(this.data);
});
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
And I would like to bind it to the following HTML:
<div data-bind="text: data.name">
</div>
I've tried very different things but none are working, so if anybody has an idea on how to accomplish this.
Finally, after a long search, I've managed to find the solution.
For anyone who's intrested, here it is:
<div data-bind="template: {name: 'OfficeWebControls-Title', data: ribbonViewModel}">
</div>
And finally the script:
<script type="text/javascript">
var ribbonViewModel;
$.getJSON("Resources/Data/Ribbon.json", function(data) {
ribbonViewModel = ko.mapping.fromJS(data);
ko.applyBindings(ribbonViewModel);
});
</script>
The reason it wasn't working is two fold:
The this pointer in the call back function is not pointing to your vm
Resources:
jQuery/JavaScript "this" pointer confusion
How does the "this" keyword work?
The data property of your vm needs to be converted to an observable
The $.getJSON call will execute asynchronously and the response will be handled after the ko.applyBindings call. This means that you'll be changing the value of the data property after it's bound to the UI. For the UI to receive changes after it is bound the properties on the view model will need to be wrapped in observables.
Example
function AppViewModel() {
//remember the this pointer for the call back handler
var self = this;
//set default data to an observable
self.data = ko.observable(null);
$.getJSON("Resources/Data/Ribbon.json", function(retrievedData) {
//use self to reference properties on the vm in a call back handler
self.data(retrievedData);
console.log(self.data());
});
}
ko.applyBindings(new AppViewModel());
For this to work the view will also need to change.
<!-- ko if:data -->
<div data-bind="text: data().name"></div>
<!-- /ko -->
fiddle

Object #<HTMLDivElement> has no method 'setCapture'

After making a change to some Google Maps code, I started getting the following error whenever I attempt to click-drag the map:
Uncaught TypeError: Object # has no method 'setCapture'
Google turned up no results for this error, so I though I'd create this question.
Can you show your code??
Recently I'm having an error likely yours. I'm doing this, in my javascript code:
var components = $(".comp-div");
for ( var i = 0; i <= components .size(); i++) {
components[i].css("width"));
}
When you use [] to access an item in a jQuery array, you get the DOM element not a jQuery object, probably you are doing this or something like, so it doesn't have any jQuery methods or any google-maps method.
I changed to use .eq() function, see next example:
var components = $(".comp-div");
for ( var i = 0; i <= components .size(); i++) {
components.eq(i).css("width"));
}

JSON results into a variable and store in hidden input field

I wrote code below that is working perfectly for displaying the results of my sales tax calculation into a span tag. But, I am not understanding how to change the "total" value into a variable that I can work with.
<script type="text/javascript">
function doStateTax(){
var grandtotalX = $('#GRANDtotalprice').val();
var statetaxX = $('#ddl').val();
$.post('statetax.php',
{statetaxX:statetaxX, grandtotalX:grandtotalX},
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
// ...
});
return false;
};
</script>
Currently, $('.total-placeholder').html(data.total); is successfully placing the total number into here:
<span class="total-placeholder"></span>
but how would I make the (data.total) part become a variable? With help figuring this out, I can pass that variable into a hidden input field as a "value" and successfully give a proper total to Authorize.net
I tried this and id didn't work (see the testtotal part to see what I'm trying to accomplish)..
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
$testtotal = (data.total);
// ...
If you are using a hidden field inside a form, you could do:
//inside $.post -> success handler.
$('.total-placeholder').html(data.total);
$('input[name=yourHiddenFieldName]', yourForm).val(data.total);
This will now be submitted along with the usual submit. Or if you want to access the data elsewhere:
var dataValue = $('input[name=yourHiddenFieldName]', yourForm).val();
The "data" object you are calling can be used anywhere within the scope after you have a success call. Like this:
$.post('statetax.php',
{statetaxX:statetaxX, grandtotalX:grandtotalX},
function(data) {
data = $.parseJSON(data);
var total = data.total;
var tax = data.total * 0.19;
});
return false;
};
Whenever you get an object back always try to see with an alert() or console.log() what it is.
alert(data); // This would return <object> or <undefined> or <a_value> etc.
After that try to delve deeper (when not "undefined").
alert(data.total); // <a_value>?
If you want 'testotal' to be recognized outside the function scope, you need to define it outside the function, and then you can use it somewhere else:
var $testtotal;
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
$testtotal = (data.total);
EDIT:
The comments are becoming too long so i'll try and explain here:
variables defined in javascript cannot be accessed by PHP and vice versa, the only way PHP would know about your javascript variable is if you pass it that variable in an HTTP request (regular or ajax).
So if you want to pass the $testtotal variable to php you need to make an ajax request(or plain old HTTP request) and send the variable to the php script and then use $_GET/$_POST to retrieve it.
Hope that answers your question, if not then please edit your question so it'll be clearer.