Hi everyone I have a question. I'm working on wordpress for my project. I'm building a very silly calculator that multiplies two values entered by a user on a form, and raises the result to a power of 1.5. I modified the theme plugin in the function.php page, adding a new function that allows you to make a calculation. But I have a problem because I can't exponentially, the theme plugin doesn't recognize exponentiation.This is my code:
if (is_page ('8434-2')) {
?>
<script type="text/javascript">
function submitBAI(event){
var x= document.getElementById("BAI-x").value;
var y= document.getElementById("BAI-y").value;
var BAI = (x/ ((y) xsp(1.5)); //the problem is here how can i do esp??
log.textContent= "Your BAI = " + BAI;
event.preventDefault();
}
const form = document.getElementById("BAI-form");
const log = document.getElementById("logBAI");
form.addEventListener("submit", submitBAI);
</script>
<?php
}
How can i do x/ ((y) xsp(1.5) in my theme theme plugin?
Use either Math.pow() or Exponentiation (**) to do that calculation. Exponentiation (**) would be more succinct because you could do normal multiplication and power calculation in one line.
let calc = (2 * 3) ** 1.5;
document.querySelector('.answer').textContent = calc;
<div class="answer"></div>
Related
I am building a classified ads website (like craigslist) with: handlebars (hbs), nodejs and multer for uploading images.
I have already created my own CRUD.
Users could post their ads for free, introducing their info for each ad:
user name
email
ad title
ad description
ad city
ad category
ad images (more than one if user needs)
I have a view, list.hbs, where ads show its information:
When users clicks on ad pictures, it will open like a modal box / pop up:
Everything perfect until here.
I save pictures in my ad.model, through multer like this:
image: {
imgName:{
type:String
},
imgPath:{
type:[String]
}
}
As you can see, I store path's pictures in an array to my mongodb database (managed by mongoose).
I.e:
"image" : {
"imgPath" : [
"uploads/e3c97fb10dd4c602054bedce194464b6",
"uploads/302fe7e147932d2b868a79b1799ba3f9"
]
}
The problem is here. I 've been trying to change image after clicking in each picture and it is impossible to do it.
I have tried via , but it looks like hbs doesn't work properly and don't read variables from handlebars:
I even tried passing through helper via onclick = myfunction({{#imageHelper}}{{/imageHelper}}), but it doesn't work...
Anybody knows how to handle this in handlebars? How to add js code to this view?
Note: my modal box / pop up is made it with pure html / css, no js or jquery in there.
I can't believe my mistake, how I didn't noticed before!
If you reach this question, or any question linked to handlebars - multer - javascript DOM, please, don't forget that template variables inside an onclick element MUST be quoted.
Mistake / Error
I passed through onclick element this:
<img onclick="myFun({{ad.reference}},{{ad.image.imgPath}})" class="imgAd" id="{{ad.reference}}" src="{{ad.image.imgPath.[0]}}"/>
And to manage the src and change images clicking everywhere on the image, I tried to do this:
...
<script>
let i = 0;
//next prev image
function myFun(ref,str){
const arr = str.split(',');
const len = arr.length;
if(i < len - 1){
i = i + 1;
document.getElementById(ref).src = arr[i]
}
else {
i = 0;
document.getElementById(ref).src = arr[i]
}
}
</script>
(This script above, just for change next picture, and so on)
Remember: if you pass variables like that, not quoted, js will throw errors, because it receives a "variable" like parameter, not a string.
In this case onclick received this:
uploads/b5e01da1707382ed915f314c0c77266c //variable, not string
Correct way:
<img onclick="myFun('{{ad.reference}}','{{ad.image.imgPath}}')" class="imgAd" id="{{ad.reference}}" display="block" src="{{ad.image.imgPath.[0]}}"/>
I passed a string, not a variable:
After I quoted each handlebar variable, I passed as string.
"uploads/b5e01da1707382ed915f314c0c77266c"
Now, the script will works. I get a string that I need to transform in an array to handle it:
<script>
let i = 0;
//next prev image
function myFun(ref,str){
const arr = str.split(',');
const len = arr.length;
if(i < len - 1){
i = i + 1;
document.getElementById(ref).src = arr[i]
}
else {
i = 0;
document.getElementById(ref).src = arr[i]
}
}
</script>
With this, I was able to manage DOM in each ad, changing images after clicking with nodejs, hbs and multer.
my question seems to be already ask, but truth me the situation here is diferent.
Problem:
TypeError: this.getDoc(...) is undefined
What i already do:
-update jquery version
-test every parameters pass to the tinymce functions, everything is ok
My code:
var html = '<div class="traduce-fields"><h4></h4><div class="text-block"><textarea class="textarea-tinymce" id="textarea-' + dataLang + '"></textarea></div><div class="bt-valide-traduce" onclick="sendTraduce($(this))"><p>TO TRADUCE !</p></div></div>';
$('.traduce-bloc-text').find('.traduce-inner').html(html);
//active de nouveau tinyMCE
tinymce.init({selector: '.textarea-tinymce'});
var selector = 'textarea-' + dataLang;
tinymce.get(selector).setContent('ok');
As mentioned in my original comment, my bet is that you are trying to use TinyMCE before its fully initialized. There is a function that can tell you when its fully initialized so you can use that to set the content:
tinymce.init({
selector: 'textarea',
...
setup: function (editor) {
editor.on('init', function () {
this.setContent('Using the on init stuff!');
});
}
As it takes you time to click on your alert this is probably allowing for TinyMCE to finish loading hence the setContent() call is then working.
My cod is long and show him in JS fiddle is hard but I got something that could help you:
This code works:
tinymce.init({selector: '.textarea-tinymce'});
alert(tinymce.get(idTextarea));
var tinyMCEInstance = tinymce.get(idTextarea);
tinyMCEInstance.setContent('ok');
This not:
tinymce.init({selector: '.textarea-tinymce'});
/*alert(tinymce.get(idTextarea));*/
var tinyMCEInstance = tinymce.get(idTextarea);
tinyMCEInstance.setContent('ok');
That's very strange, what kind of problem an alert could solve?
Thank you for helping me.
Using SkyScanner's white label API, I'm trying to add the following to a Wordpress webpage...
The code works fine when placed into the body of a simple webpage. Can anyone let me know how to get it to work in a WordPress page? I'm creating/editing the page via wp-admin. I'm using a standard template.
Thanks in advance.
<div id="wl-container"></div>
<script>
(function (s, k, y) {
var l = s.createElement("script");
l.src = k + "/js/client.js"; l.async = 1;
l.onload = function () { y({ serviceBase: k }); };
var t = s.getElementsByTagName("head")[0]; t.appendChild(l);
})(document, "//whitelabel.api.skyscanner.net", myCallback);
function myCallback(options) {
var whitelabel = new Skyscanner.Flights.Whitelabel({
serviceBase: options.serviceBase,
customerId: "testwl46"
});
whitelabel.create("wl-container", {
market: "UK",
locale: "en-GB",
currency: "GBP",
originPlace: "EDI",
destinationPlace: "LON",
outboundDate: "2014-03-10",
inboundDate: "2014-04-10"
});
}
</script>
thanks for using our Skyscanner White Label.
I see you finally managed, by the way using WordPress there is a couple of things you should follow in inserting Javascript code:
Use Text Editor option instead of Visual Editor
Have a look at this page http://codex.wordpress.org/Using_Javascript as there are some rules in using Javascript within WP
Hope this helps in case you still have problems
I finally manage to get this to work by being very careful with the indenting, spaces and line breaks when entering the javascript within the wordpress page editor
Thank you.
<div id="wl-container"></div>
<script>
(function (s, k, y) {
var l = s.createElement("script");
l.src = k + "/js/client.js"; l.async = 1;
l.onload = function () { y({ serviceBase: k }); };
var t = s.getElementsByTagName("head")[0]; t.appendChild(l);
})(document, "//whitelabel.api.skyscanner.net", myCallback);
function myCallback(options) {
var whitelabel = new Skyscanner.Flights.Whitelabel({
serviceBase: options.serviceBase,
customerId: "testwl46"
});
whitelabel.create("wl-container", {
market: "UK",
locale: "en-GB",
currency: "GBP",
originPlace: "EDI",
destinationPlace: "LON",
outboundDate: "2014-03-10",
inboundDate: "2014-04-10"
});
}
</script>
I had hard time with this and finally resolved it by installing this plugin from Amazon https://s3.amazonaws.com/videomaster/plugins/simple-js-paste.zip
You can put your javascript code in it, and in the text field put skyscanner div. I wish this help.
I've looked on Google's product forums, and I can't find anything. The help text field is designed for brief text, but I want to insert a mulit-paragraph article. Without paragraph breaks, I wind up with a bunch of text that's difficult to read.
This has been bugging me for a long time and I've came up with a not so elegant but efficient solution based on Apps Script. Pavel Agarkov had the same idea! My version also works with multiple occurences and can be re-run if Google Forms removes the line breaks when you edit the text.
When editing a form, open the Script Editor from the main menu.
Create a new script, replace the content with the code below. Save it and return to your form.
Reload the page. You will notice a new option in the main menu, looking like this
That "Scripts" menu was added by our script. Don't use it for now, it won't do much.
When editing content, use fours spaces as a placeholder for line breaks.
Run the script from the Scripts menu. Now celebrate 👯♀️
Some things worth noting:
You will get a permission request the first time you run the script. It's ok, read the message and do what you have to do.
Once the line breaks are there, Google Forms, god bless its heart, will remove them every time you edit the field. Mildly infuriating. Just run the script again.
The script you need to use is:
// From https://stackoverflow.com/questions/22207368/
function onOpen() {
var ui = FormApp.getUi();
ui.createMenu('Scripts')
.addItem('Replace 4+ spaces with line breaks in Title and Description', 'addLineBreaks')
.addToUi();
}
function addLineBreaks() {
var theForm = FormApp.getActiveForm();
var theQuestions = theForm.getItems();
var thePlaceholder = new RegExp(/\s{4,99}|\n/, 'gi');
for (i = 0; i < theQuestions.length; i++) {
var theText = theQuestions[i].getHelpText();
if (theText.search(thePlaceholder) > 0 ) {
theQuestions[i].setHelpText(theText.replace(thePlaceholder,' \n'));
}
theText = theQuestions[i].getTitle();
if (theText.search(thePlaceholder) > 0 ) {
theQuestions[i].setTitle(theText.replace(thePlaceholder,' \n'));
}
}
}
I found that you can't do it through the editor but it is possible via the script.
Go to main menu -> script editor;
past the following code to the editor;
function addLineBreaks()
{
var form = FormApp.getActiveForm();
// find form items you need
var questions = form.getItems(FormApp.ItemType.MULTIPLE_CHOICE);
for(i = 0; i < questions.length; i++)
{
var title = questions[i].getTitle();
// if no replacement has been done yet
if(title.indexOf("\n") < 0)
{
// this will add line break after <double space> like in markdown
questions[i].setTitle(title.replace(" ", " \n"));
}
}
}
then set up trigger to start this method on form open.
I struggled with this question myself for too long!
However, when you know how its simple:
Go to "Add Item"
Choose "Section Header"
This option allows you to put paragraphed text into your Form.
As of June, 2018, the following work (but only the second option is documented):
Just put new lines in the description and it will be shown in the form - try using two for a paragraph.
If you want a bit more style - add a 'Title and Description' - see the second option in the tool bar showing 'Tᴛ'. The Title will always add extra space (even if it's empty) and will show any title as inverted, larger, text. You can disable the description if you just want a 'heading' followed by questions.
None of the above solutions worked for me, SO I added a unicode character https://www.compart.com/en/unicode/U+2002 pasted 4 to 5 times and this is how it looks
Sorry for the bad news, but this seems impossible to me.
I found the answer! While in the box into which you are entering text, go to Properties in the Developer tab. You will get a drop-down menu. At the bottom of the menu is "Plain Test Properties" with a check box for "Allow carriage returns (multiple paragraphs).
This is a better solution but based on the above. It allows you to edit the form which amazingly the above solutions don't:
// Version 2020-10-07a: by Dennis Bareis
// Handles "{nl}" in form & question descriptions
// Forms API: https://developers.google.com/apps-script/reference/forms
// Based on https://stackoverflow.com/questions/22207368/
// This code #: https://stackoverflow.com/a/64216993/3972414
// [0] ... -> Script Editor -> Create New Script
// [1] Paste into script editor
// [2] Run onOpen()
// [3] On first run authorise script
// [4] This adds 2 scripts under a new button in the edit form UI
// (to the left of the "Send" button)
// [5] Use "START" before re-editing form
// [6] Use "END" to publish the changes
// 5&6 required as otherwise you end up with "line1Line2Line3" etc
String.prototype.replaceAll = function(search, replacement)
{
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
//This doesn't perform the function on open, just adds it to the UI, you run when finished.
function onOpen()
{
var ui = FormApp.getUi();
ui.createMenu('Scripts')
.addItem('[1] Prepare for RE-EDITING this form (restore {nl})', 'editFormStart')
.addItem('[2] Publish the form (finished editing, remove {nl})', 'editFormEnd')
.addToUi();
}
function editFormStart()
{
swapLineBreaks("\n", "{nl}")
}
function editFormEnd()
{
swapLineBreaks("{nl}", "\n")
}
function swapLineBreaks(FromText, ToText)
{
var form = FormApp.getActiveForm();
// find form items you need
var oForm = FormApp.getActiveForm();
var questions = oForm.getItems();
// Fix the form's description
var formDesc = oForm.getDescription()
oForm.setDescription(formDesc.replaceAll(FromText, ToText))
// Work through each question
for(i = 0; i < questions.length; i++)
{
//var QTitle = questions[i].getTitle();
//questions[i].setTitle( QTitle.replaceAll(FromText, ToText));
var QText = questions[i].getHelpText();
questions[i].setHelpText(QText.replaceAll(FromText, ToText));
}
}
Okay I'm trying to add comments and reactions count just like what you would normally see on some wordpress blogs like http://johntwang.com/blog/ where on the left top of each post there is ** comment and * reactions*
(source: windows7hacker.com)
My problem is I can't find the disqus's documentation, where hopefully there is some method I can call to return me the number of reactions and comments. Also if I use the wordpress default method
<?php comments_popup_link ('zero','one','more','CSSclass','none');?>
it only displays "Comments" not even the comment's number count on the main page.
How can I add reaction and comment count with disqus plugin ?
edit:
well my site is http://www.windows7hacker.com/ I don't know how I suppose to add comments count at first place. But right now if I use the wordpress method, it will return me only comments, which is exactlly one of the problem they have described in their help page
(source: windows7hacker.com)
I've tired to check the comment count option still doesn't work :(
I've never used the wordpress plugin. But I have used the JS only version.
You can get JS only Disqus working pretty quickly by doing the following.
Add this JS to your page.
<script type="text/javascript">
//<![CDATA[
(function() {
var links = document.getElementsByTagName('a');
var query = '?';
for(var i = 0; i < links.length; i++) {
if(links[i].href.indexOf('#disqus_thread') >= 0) {
query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&';
}
}
document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/ohu/get_num_replies.js' + query + '"></' + 'script>');
})();
//]]>
</script>
Add this code to where you want the comments to display (so probably underneath the post text)
<div id="disqus_thread"></div><script type="text/javascript" src="http://disqus.com/forums/ohu/embed.js"></script><noscript>View the discussion thread.</noscript>blog comments powered by <span class="logo-disqus">Disqus</span>
Finally - to get the comment count to show. All you need to do is append #disqus_thread to your permalink URL in any tag... so for example...
Comments
would become...
Comments
And that will replace "Comments" with x Comments... (x being the number of comments for that post).
I'm a little rusty with wordpress templates so I'm not 100% sure where you would put all of that. But if you have anymore questions I can try to help out.
I know there is a wordpress plugin for disqus. However if you want to set it up just using plain old js, disqus provides a snippet for you to use in their Universal Instructions page
http://disqus.com/comments/universal/YOURDISQUSACCOUNT
This is the comment snippet they provide
<script type="text/javascript">
//<![CDATA[
(function() {
var links = document.getElementsByTagName('a');
var query = '?';
for(var i = 0; i < links.length; i++) {
if(links[i].href.indexOf('#disqus_thread') >= 0) {
query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&';
}
}
document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/YOURDISQUSACCOUNT/get_num_replies.js' + query + '"></' + 'script>');
})();
//]]>
</script>
The Instructions default page is here http://disqus.com/comments/install/YOURDISQUSACCOUNT
This page is actually quite hard to get to...