generating HTML with javascript that contains php and ifs [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a large amount of HTML and CSS which contains some PHP (session based content) this PHP is a must. I need that session information (no cookies wont do).
The html and CSS are standard divs I am looking at this previous question:
Is there a best practice for generating html with javascript
which gives me the answer I need, if I was using just HTML and CSS, but what about if I need to use JS if statements to chose what part of the template needs to be different and what if I need to use PHP to do the same?
I am moving my code away from heavy server side scripting and moving as much as I can to front end processing, but the issue is I need to have some PHP and if statements (js if statements) within the $.template
can I use PHP variables in a JS templating system and how do I use JS IF statements within the templating function?
var moo = 1
var T = $.template('<div>This is code, but what is moo?. if(moo == 1){moo was 1..}else{moo was not 1}</div>')

As I commented, you can declare and check your variables before using it.
Example:
var moo = 2 + 2 == 4 ? "yes moo" : "no moo";
var T = $.template('<div>This is code, but what is moo?. Moo is '+ moo +'</div>');
But if you are working with large data, you should consider to use a string variable and concatenate the new strings as needed:
var str = "<div>";
if( moo == 4 ) str += "moo equals 4";
else str += "moo NOT equals 4";
str += "</div>";
// And when you have your string completed...
var T = $.template(str);
By this way you can concatenate all you need without headaches.

Related

Is there a way that this is possible? I am trying to find a value of a var constructed by other variables [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
This is a little bit of my code. I took out the complex parts. It is all on the script tag.
var trueenemyscoutx = '_2'
var tryeenemyscouty = '2'
var type_22 = "none"
var move1;
enemymove = "type" + trueenemyscoutx + trueenemyscouty;
var move1 = (enemymove.valueOf()).valueOf()
In the post, enemymove is a string constructed by concatenating "type" and two other variables, each of which is also a string.
The resultant string contains no information about the variables used and so the general answer to the question is no, it is not possible using the approach taken.
Obvious alternatives include:
Keep move a string, but use a separator (e.g. colon, comma or space) between component substrings. This allows extracting an array of the components using move.split(separator).
Use an array or simple object to hold move information instead of a string in the first place.

HTML tag not working in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am outputting some information from my database using JavaScript. Some of this information includes HTML tags, such as <sub>. The error I'm getting in my browser is
Invalid regular expression: missing /
My guess is that JavaScript is having a problem with the closing tag in </sub>. How can I make a forward slash work in javascript?
Here is some example code, in case you would need it:
echo "
<script>
function wikitoCalculator() {
document.getElementsByName('chemicalsearch')[0].value = $name;
var userChemical = document.getElementsByName('chemicalsearch')[0].value;
if (userChemical.toLowerCase() === 'vatten') {
var formel = $vatten3[namn2];
var massa = $vatten3[molmassa];
document.getElementById('formel').innerHTML = formel;
document.getElementById('atommassa').innerHTML = massa;
}
}
</script>
";
As you can see, Im simply trying to output some information from a PHP variable that is taken from a database, through JavaScript into the HTML. Nothing is getting outputted, and Im getting the error stated above.
It looks like you need to wrap your php variables with string quotes. Your JavaScript is coming out like myString = <sub> blah blah </sub> when it should be myString = "<sub> blah blah </sub>"
Wrap your php variables in quotes "$myVar"
In your particular case it might be
document.getElementsByName('chemicalsearch')[0].value = "$name";
The problem is this
var formel = $vatten3[namn2];
var massa = $vatten3[molmassa];
This may work but I can't remember if double quotes allows arrays as well as primitive type variable either you should change to this.
var formel = $vatten3['namn2'];
var massa = $vatten3['molmassa'];
You forgot the single quotes for the associative names in the array.
P.S. Sorry if the formatting is weird I'm doing this from my phone, I fix it as soon as I get to a computer.

Compiling LESS color definitions to JavaScript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a LESS file with color definitions:
#RED: #CE1512;
#BLUE: #3E83A0;
// ...
I now have need of using these color definitions in my JavaScript as well.
How best to share code like this between LESS and JavaScript?
I ended up coming up with my own solution, though I think I will try to avoid using it all-together (per the reasons listed by alttag).
Vohuman's answer provides another solution, but I don't really like the idea of embedding js directly in my LESS file, so would prefer an approach like below.
I created the following node.js module which will read a json file and output a less file.
var fs = require('fs');
var EOL = require('os').EOL;
module.exports = function (jsonFile, outputFileName) {
var json = require(jsonFile);
var lessFileContent = "";
for (color in json) {
var lessColorDefinition = '#' + color + ': ' + json[color] + ';';
lessFileContent += lessColorDefinition + EOL;
};
fs.writeFile(outputFileName, lessFileContent);
};
Example json file:
{
"RED": "#CE1512",
"BLUE": "#3E83A0"
}
Example usage in Gulp task:
var j2l = require('./baseStyles/jsonToLess');
gulp.task('build-base-less', function() {
j2l('./colors.json', 'colors.less');
});
The short answer to one of your questions is no, no it is not a good idea to use it in your javascript. In general, it is best to keep color and other visual information in CSS, and behavior information in javascript.
Exceptions should be exceedingly rare.
Is this even a good idea?
It depends on the application needs and how it's structured. If you have so many variables and your JavaScript heavily needs them then it makes sense. Otherwise having duplicates in both environments can be considered too.
Which should be the pre-compiled source? (js or less)
JavaScript as LESS compiler also understands JavaScript; however, JSON, in this case is the best option.
Does something like this already exist?
You could create a json file and import it in your LESS file. In JavaScript the file can be easily loaded by using Ajax.

Extra tags on the end of a URL for different pages [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Hello I really want to learn how to do something like this. If you go to a page for example it says http://example.net/search.html?catagory=food&includelevelone=true. I do not have access to php so it can only be HTML and Javascript/jQuery. Thanks in advance!
The part of the URL that is from the questionmark onwards is called a query string.
Here is a pure JavaScript function to parse the query string to obtain particular values:
function querystring(key)
{
var filter;
var value;
key = key.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
filter = new RegExp('[\\?&]' + key + '=([^&#]*)');
value = filter.exec(window.location.search);
if(value == null)
{
return '';
}
else
{
return decodeURIComponent(value[1].replace(/\+/g, ' '));
}
}
You just pass in the query string key name you're interested in (as a string) and you get the value back (also as a string.) An example of how you could use the function:
alert('Category = ' + querystring('catagory'));
Everything behind the questionmark is a url parameter. every word left of an equal sign is the name of the parameter, everything right of an equal sign is the corresponding value. The name-value-pairs are divided by &-signs
Here are two pages i quickly googled that are about getting these parameters in JavaScript (wich is really not that hard):
http://code-tricks.com/get-url-parameters-using-javascript
http://ziemecki.net/content/javascript-parsing-url-parameters

How to get the final result of javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an html page with a lot of javascript code, for example the content of a div depends on length of an array :
for (var i = 0; i < movieList.length; i++) {
document.body.appendChild(document.createElement('h2')).appendChild(document.createTextNode('title: ' + movieList[i].title));
var cUL = document.body.appendChild(document.createElement('ul'));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode(movieList[i].rating));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode(movieList[i].year));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode(movieList[i].length));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode(movieList[i].isComedy));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode('main characters: ' + movieList[i].mainCharacters.join(", ")));
}
I am using these perl LWPx::ParanoidAgent and HTML::TokeParser modules to handle the HTML code but the i want the result of the javascript script
You either need to:
Reverse engineer the JS and apply the changes it would make manually or
Run the HTML and JS through a browser or browser-like tool and read the data from its DOM
There are a number of options for the latter, including WWW::Mechanize::Firefox, WWW::Selenium and Wight.
perhaps https://getfirebug.com/ is what you're looking for. Amongst loads of other things you can view your HTML after JavaScript has altered it.

Categories

Resources