I am getting an $("<div/>").text(value).html is not a function error in the code below:
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
function startImageUpload(imageuploadform, imagefilename){
$('.imagef1_cancel').eq(window.lastUploadImageIndex).html(
'<div>' +
htmlEncode(imagefilename) +
'<button type="button" class="imageCancel" cancel_image_file_name="' +
imagefilename +
'">CANCEL</button></div>'
);
return true;
}
How can this error be fixed?
The strange thing is I have a similar code below but different function (stopImageUpload) and the code works fine below:
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
function stopImageUpload(success, imagefilename) {
imagecounter++;
$('.listImage').eq(window.lastUploadImageIndex).append(
'<div>' +
htmlEncode(imagefilename) +
'<button type="button" class="deletefileimage" image_file_name="' +
imagefilename +
'">Remove</button><br/><hr/></div>'
);
return true;
}
Link to application to see what is happening is here: application
$('<div/>').html(value); //without text function
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
If value in the above snippet is undefined, then text() returns the DOM Element's text content, not the element itself, causing the chained call to fail.
Related
I need to display user input inside the div. But if the user put in tag, it will execute whatever inside the script tag.
For example
<html>
<body>
<button onclick="runTest('<script>alert(\'test\')</script>')">Click Me</button>
<div id="test"></div>
</body>
</html>
And my javascript runTest function
function runTest(str) {
$('#test').append($('<div>' + str + '</div>'));
}
If I run this, it will cause alert() to be executed. I tried to use escape(str), but it displays the escape characters %3Cscript%3Ealert%28%27test%27%29%3C/script%3E
Any idea? Here is the fiddler: https://jsfiddle.net/zvLg1w6q/1/
Thanks...
you can use this function:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
and use it same as follow:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
document.getElementById("myDiv").innerHTML = htmlencode('<scrip t>alert("hi")</scrip t>')
<div id="myDiv">
</div>
I am trying to build a Javascript class which takes some options and returns builds a form. I would like the submit function to be determined by the options passed to the class. All of the HTML is output as expected, but I don't think the javascript that is being output is being parsed. When the HTML renders I get a syntax error -
"Unexpected token function"
and when I try to submit the form I get a
Reference error - "{functionName} is not defined."
Here is the class so far:
var ClassOptionsForm = function(options) {
this.options = options
this.getSubmissionFunction = function() {
switch (this.options.type) {
case 'standard':
return this.standardSubmit;
break;
case 'extendable':
return this.extendableSubmit;
break;
}
}
this.successHandler = "function (data, form) {\
$(form).find('.result').text('Success!').css('color', 'green');\
}"
this.failureHandler = "function (data, form) { \
$(form).find('.result').text('Something went wrong.').css('color', 'red');\
}"
this.submitFunctionName = this.options.optionName + "Submit";
this.standardSubmit = "function " + this.options.optionName + "Submit(form) {\
google.script.run\
.withSuccessHandler(" + this.successHandler + ")\
.withFailureHandler(" + this.failureHandler + ")\
.withUserObject(form)\
.setUserOption('" + this.options.optionName + "', form)\
}"
this.extendableSubmit = "function(this) {\
// Extendable Form Submit
}"
this.buildForm = function() {
var value = this.options.value;
return '\
<script type="text/javascript">\
' + this.getSubmissionFunction() + '\
</script>\
<h3>' + this.options.formTitle + '</h3>\
<form id="' + this.options.optionName + '" onsubmit="' + this.submitFunctionName + '(this)">\
' + Object.keys(value).reduce(function(list, key) {
return list + '<input name="' + key + '" value="' + value[key] + '"/>';
}, '') + '\
<button type="submit">Save</button>\
</form>\
'
}
}
And here is how form render function is called in the HTML file:
<?!= GoogleAnalytics().optionsForm.buildForm(); ?>
And here is the final HTML output:
<script type="text/javascript">
function UAIDSubmit(form) {
google.script.run
.withSuccessHandler(function (data, form) {
$(form).find('.result').text('Success!').css('color', 'green');
})
.withFailureHandler(function (data, form) {
$(form).find('.result').text('Something went wrong.').css('color', 'red');
})
.withUserObject(form)
.setUserOption('UAID', form)
}
</script>
<h3>UAID</h3>
<form id="UAID" onsubmit="UAIDSubmit(this)">
<input name="id" value="********">
<button type="submit">Save</button>
</form>
I am pretty sure that this has something to do with the way that App Script sanitizes HTML, and I know there are a million ways I could accomplish submitting the form without dynamic JS. I am just trying to keep my code as dry as possible, and also I'm curious. Any workarounds that keep that don't involve doing away with templated JS?
When you try to submit the form it won't work because you can use a form object as parameter in a Google Script function but the form object must be the only parameter in that function. Read here[1]
[1] https://developers.google.com/apps-script/guides/html/reference/run
I have an HTML textarea defined in index.html defined as follows:
<textarea id="myTextArea" rows="12" readonly="7" class="form-control"></textarea>
I have a JavaScript file named shared.js. Right now, shared.js only has the following:
function appendToTextArea(id, text, stayOnCurrentLine) {
var current = $(id).val();
var newText = current + ' ' + text;
if (!stayOnCurrentLine) {
newStatus += '\n';
}
$(id).val(newText);
console.log($(id).val());
}
Index.html is successfully referencing shared.js. It even calls appendToTextArea just fine. I'm calling the code from a function in index.html called myButtonClick.
function myButtonClick() {
appendToTextArea('#myTextArea', 'Hello', false);
appendToTextArea('#myTextArea', 'How', false);
appendToTextArea('#myTextArea', 'are', false);
appendToTextArea('#myTextArea', 'you', false);
}
When the above is called, the text of myTextArea is never updated. However, in the console, I see no errors. In addition, I can see the text exactly how I would expect it. What am I doing wrong?
Define newStatus as empty string and concatenate it with outputted string:
function appendToTextArea(id, text, stayOnCurrentLine) {
var current = $(id).val();
var newStatus = "";
var newText = current + ' ' + text;
if (!stayOnCurrentLine) {
newStatus += '\n';
}
$(id).val(newText + newStatus);
console.log($(id).val());
}
-jsFiddle-
I am creating a BF4 weapon selector (tells you random weapons/attachments to equip), using the function below, and a link to refresh it (to run the function again), however when the link is clicked, it does not work (and there is no error in console)
Any ideas? JSFiddle
Just to clarify: the text appears, and as a link, however when you click the link (which runs javascript:CreateWeapons(), it does not work, and there is no error in JSFiddle, or in javascript console)
JS:
function Random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function CreateWeapons() {
document.getElementById('text').innerHTML = ('<a href="javascript:CreateWeapons();">' +
'Primary: ' + Primary +
'<br>' +
'Secondary: ' + Secondary +
'</a>');
}
var Primary = Random(["M16A4", "M16A3", "M416", "None"]);
var Secondary = Random(["None",".44 Deagle"])
CreateWeapons();
// BF4 weapon chooser (using random values)
HTML:
<div id="weapons">
<div id="text"></div>
</div>
If you want the Primary and Secondary weapons to change in each click, you have call Random method inside the CreateWeapons method.
Also it is not good way to use href to call js function, you can use onclick instead of that.
Here is the updated working code for you.
function Random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function CreateWeapons() {
var Primary = Random(["M16A4", "M16A3", "M416", "None"]);
var Secondary = Random(["None",".44 Deagle"]);
document.getElementById('text').innerHTML = ('<a href="#" onclick="CreateWeapons();return false;">' +
'Primary: ' + Primary +
'<br>' +
'Secondary: ' + Secondary +
'</a>');
}
CreateWeapons();
// BF4 weapon chooser (using random values)
It's better if you create an element and then use it's onclick event to call the function rather using the inline onclick event. Try this,
function Random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
var aElement = document.createElement("a");
aElement.href="#";
function CreateWeapons() {
var Primary = Random(["M16A4", "M16A3", "M416", "None"]);
var Secondary = Random(["None",".44 Deagle"]);
aElement.innerHTML = ('Primary: ' + Primary + '<br />' + 'Secondary: ' + Secondary);
document.getElementById('text').appendChild(aElement);
return false;
}
aElement.onclick = CreateWeapons;
CreateWeapons();
jsFiddle
$(document).on("pageshow", "#mappage", function (event) {
$("#doldur").append("<li> <label onclick='getBina("
+ featuressokak[f].attributes.SOKAKID
+ ");'>"
+ featuressokak[f].attributes.SOKAKADI
+ "</label><div onclick='findsokak(" + f + ");' style='float:right;width='20%''><img src='img/map.png' style='float:right;'/></div></li>");
function getBina(sokakid) {}
});
I wrote part of my code. I need to call function getBina inside on mappage function. But I got this error : uncaught ReferenceError: getBina is not defined. So when I wrote function getBina outside mappage function, logicically I got error. I must run on inside. how is it possible ?
my button code :
var content = '<div class="adresbaslik">'+feature.attributes.ADI+'</div><p style="margin-top:-10px"></p><div class="fulladrespopup">'+mahalleadi+' MAHALLESİ '+sokfeature[0].attributes.SOKAKADI +' SOKAK NO:' + numfeature[0].attributes.KAPINO +' '+ilceadi+'</div>' ;
content = content + '<p style="margin-top:-10px"></p><div style="text-align: center ;"><a data-ajax="false" onclick="sendForm("'
+ilceadi+'","'
+mahalleadi+'","'
+sokfeature[0].attributes.SOKAKADI+'","'
+ numfeature[0].attributes.KAPINO+'","'
+ ilcegisID+'","'
+ mahallegisID+'","'
+ sokgetir[0].attributes.GIS_ID+'","'
+ numfeature[0].attributes.KAPINO+'","'
+ feature+'"'
+');" class="formgidin" >Bildirim</a></div>';
write the definition of the function then only it will remove the error "getBina is not defined".
You can write the function globally or you can write function locally.