adding math formula string to document using javascript and MathJax - javascript

When pressing the button to add the math formula, the MathJax statement does not seem to be interpretet:
const button = document.getElementById('go');
button.addEventListener('click', displayMath, true);
function displayMath() {
const body = document.body;
p = document.createElement('p');
const a = 3, b = 2;
const c = a + b;
const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
p.innerHTML = math;
body.appendChild(p);
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async>
</script>
</head>
<body>
<p>press the button to display math like this: \(a + b = c\)</p>
<button id="go" type="button">Go!</button>
<script src="test.js"></script>
</body>
</html>
1) Can MathJax statements be addet through events like a button click?
2) If not are there better alternatives?
I appreciate any help, thanks :>

You need to run Mathjax parser again, to convert dynamically added expression to math. Here is documentation.
So, what you need to do is run MathJax.Hub.Queue(); method on your new expression. Your code should looks like this:
const button = document.getElementById('go');
button.addEventListener('click', displayMath, true);
function displayMath() {
const body = document.body;
p = document.createElement('p');
const a = 3, b = 2;
const c = a + b;
const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
p.innerHTML = math;
body.appendChild(p);
MathJax.Hub.Queue(["Typeset", MathJax.Hub, p]);
}
And here is working fiddle

Related

javascript getElementById outside function does not work

I am relatively new to javascript and made this simple guess the number program. My question is this:
Why does it only work if:
var myNumber = document.getElementById("myNumber").value;
is defined within the function. I thought that if it was defined outside the function it will have "scope to b used within it?
Thank you for any help.
<p> Enter your number 1-10 <input id="myNumber" type="text"> </p>
<button id="btn1">Go</button>
<script type="text/javascript">
document.getElementById("btn1").onclick = function() {
var myNumber = document.getElementById("myNumber").value;
var number = parseInt(myNumber);
var count = 1;
var computerGuess = Math.floor((Math.random() * 10) + 1);
while (computerGuess !== number) {
computerGuess = Math.floor((Math.random() * 10) + 1);
count++;
}
alert("you guessed it" + " in " + count + " guesses");
}
</script>
When you will use document.getElementById in global scope it will return undefined if
the script is above the element which you wanna access. Because it can get element by id before it is created
Solution 1. Use all your script tags at last of all elements
Solution 2. use this way
<!DOCTYPE html>
<html>
<body>
<script>
var globalElm;
function start(){
globalElm = document.getElementById('elm')
}
setTimeout(start,50);
</script>
<div id="elm"></div>
</body>
</html>

Scaling image using variables

Im trying to scale an image using variables rather than a set in stone scale. I know using "scale(0.5,0.5)" works but I want to do something like "scale(x,y)" so the scale factor changes depending on what variables x and y are, However when I try doing this, the image will no longer scale like it did when it had a set scale factor. How can I solve this? Thanks for any help. Here's an example of what I mean.
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="img_pulpit.jpg">
<button onclick="myFunction()">Try it</button>
<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale(f, i)";
}
</script>
</body>
</html>
Just use string concatenation ("scale(" + f + ", " + i + ")") or string interpolation (`scale(${f}, ${i})`).
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale(" + f + "," + i + ")";
}
You need to use concat the value of f and i
document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="https://lh3.googleusercontent.com/gN6iBKP1b2GTXZZoCxhyXiYIAh8QJ_8xzlhEK6csyDadA4GdkEdIEy9Bc8s5jozt1g=w300">
<button onclick="myFunction()">Try it</button>
<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";
}
</script>
</body>
</html>

JS. How do I create a regex pattern by concatenation with variables

I am not able to fix the following:
<html>
<head>
<title>Test</title>
<script>
function myFunction(arr) {
var N = [0,1,2,3,4,5,6,7,8,9];
for (var s in N) {
var pattern = new RegExp('/^[A-z]et_[' + s + ']_\\d/');
// NOTE I get the following, is that how it should be?
// window.alert(pattern); => /\/^[A-z]et_[0]_\d\//
// NOTE: I checked that it works fine for a single digit case, say:
// var pattern = new RegExp(/^[A-z]et_[3]_\d/);
var newarr = arr.filter(elt => pattern.test(elt));
document.getElementById("demo").innerHTML = newarr;
}}
</script>
</head>
<body>
<div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_', 'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
<hr>
<p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
</body>
</html>
I see many similar questions, but I have not been able to find out how to fix my code. It should be possible, shouldn't it?
EDIT
the following is what I need:
<html>
<head>
<title>Test</title>
<script>
var newarr = [];
function myFunction(arr) {
var N = [0,1,2,3,4,5,6,7,8,9];
for (var s in N) {
var pattern = new RegExp('^[A-z]et_' + s + '_\\d'); // NOTE: not /
var lnewarr = arr.filter(elt => pattern.test(elt));
if(typeof lnewarr !== 'undefined' && lnewarr.length > 0){newarr.push(lnewarr)};
}
document.getElementById("demo").innerHTML = newarr;
}
</script>
</head>
<body>
<div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_', 'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
<hr>
<p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
</body>
</html>
(sorry if my post is mostly code. Hope it may helps somebody out there.)
Instead of for loop you can use a .join like this:
var pattern = new RegExp('^[A-Za-z]et_[' + N.join('') + ']_\\d');
//=> /^[A-Za-z]et_[0123456789]_\d/
This works for the case when you have singe character values in your array N.
For generic use you can use this expression:
var pattern = new RegExp('^[A-Za-z]et_(?:' + N.join('|') + ')_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/
Using a for loop you can do this:
var N = [0,1,2,3,4,5,6,7,8,9];
var str='(?:';
for (var s in N)
str += s + '|';
str = str.replace(/\|$/, ')');
var pattern = new RegExp('^[A-Za-z]et_' + str + '_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/

The functions aren't cooperating :/

function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
document.getElementById("input").innerHTML = "<input id=>";
document.getElementById("check").innerHTML = "<button>Check</button>";
}
function myBunction() {
myFunction();
var b, text;
// Get the value of the input field with id="numb"
b = document.getElementById("input").value;
var D = document.getElementById("demoX").value;
var E = document.getElementById("demoY").value;
// If x is Not a Number or less than one or greater than 10
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
}
<p>Click the button to display a random number between 1 and 10.</p>
<button onclick="myFunction()">Try it</button>
<br> <br>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id=equal></span>
<span id=input></span>
<span onclick="myBunction()" id=check></span>
<p id="demo"></p>
The first function throws two random numbers and the second one should check if the input form person is correct but "document.getElementById("demoX").value" returns nothing ... I was trying check values with console.log but it returns like nothing is define.
I was just trying to merge two functions from w3schools but it took me so much time. :/
Your problem is four-fold. One:
document.getElementById("demoX").value
does not return anything. A <span> element has no value. It has an innerHTML, just what you used to set it.
Two:
if (b == E + D) {
E and D will be strings. The result of adding two strings is a combined string.
"4" + "3" is not "7", it is "43".
You want to convert them to numbers first. Among other things, an unary + can do that. Try:
b = +b;
D = +D;
E = +E;
if (b == E + D) {
Three: You want to reset the form after you read out all values, not before.
Four: What's all that business creating all those fixed input fields and buttons dynamically via innerHTML anyway? Just put them into the HTML directly and let them sit there.
So...
function reset() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("input").value = "";
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
}
function check() {
var b, D, E, text;
// Get the value of the input field with id="numb"
b = +document.getElementById("input").value;
D = +document.getElementById("demoX").innerHTML;
E = +document.getElementById("demoY").innerHTML;
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
reset();
}
reset();
<p>Click the button to display a random number between 1 and 10.</p>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id="equal"></span>
<input id="input">
<button onclick="check()">Check</button>
<p id="demo"></p>
Solved and nicer code.
Test
<script>
//=====|Generate the problem|=====//
function myGenerator() {
var x = Math.floor((Math.random() * 100) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 100) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
document.getElementById("numbs").innerHTML = "<input id=numb>";
document.getElementById("check").innerHTML = "<button>Check</button>";
}
//=====|Check the given solution|=====//
function myChecker() {
var a, text;
a = document.getElementById("numb").value;
var b = parseFloat(document.getElementById("demoX").textContent);
var c = parseFloat(document.getElementById("demoY").textContent);
//=====|Simple if|=====//
if (a == b + c) {
alert("Congratulation");
text = "Right";
} else {
alert("Maybe next time");
text = "Wrong";
}
document.getElementById("demo").innerHTML = text;
//=====|Just for control|=====//
console.log(a);
console.log(b);
console.log(c);
}
</script>
<h1>Click to start</h1>
<button onclick="myGenerator()">Try it</button>
<br>
<br>
<!--=====|Hidden Stuff|=====//-->
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id="equal"></span>
<span onclick="myChecker()" id=check></span>
<span id="numbs"></span>
<!--=====|Response|=====//-->
<p id="demo">

function is not working in my code

my problem is that text3 is undefined in my codes in here:
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
but it is here:
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
here is all of my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
</script>
</body>
</html>
what is the problem?
please help
Looks like $('#x').keyup() is being called before $('#pass').keyup()
Your call $('#x').keyup(function (e) { is creating the first event listener so on keyup you will always endup with text3 is undefined because the $('#pass').keyup(function (e) { will be triggered always later.
EDIT:
Your second keyup handler will never work because it will grab the #pass element only once (during document parse). You need to create some defered listener to fix it.
// Anyway this won't fix your text3 is undefined problem.
What you need to do is define it first before the two .keyup handlers.
NOTE:
But please avoid setting global variables anyway ;)
Put everything into a closure or something.
Last but not least DO NOT create many elements with the same ID this is a major bug.
Look, even after fixing the code to get it to work it makes very little sense. Using roryok's jsFiddle, it'll only work if the value you're entering is a number and doing so just spawns the paragraph elements for the number you entered. You can enter as many numbers as you'd like (before your browser crashes), it'll always return as "weak".
If it's a simple password strength meter you're after, unless you can explain the logic you're trying to achieve more by forcing it to stick to numbers, I'd dump most of the JavaScript code and reduce it to
$('#x').keyup(function (e) {
document.getElementById("passdiv").innerHTML = strength($(this).val());
return true;
});
function strength(val) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test(val)) {
t = "strong";
} else if (normal.test(val)) {
t = "normal";
} else {
t = "weak";
}
return t;
}
This will then validate the whole input each time you enter a character, which the user can then submit once it's "strong".
Here's my jsFiddle: http://jsfiddle.net/xqooj482/
text3 is not set as a variable in your code, therefore it's always going to be undefined. You need to set it before your two functions.
Note: I also put things inside a jQuery ready function.
For some reason I'm being downvoted, but I tested this and it works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
// set text3 in here first
var text3 = "";
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
});
</script>
</body>
</html>
Also here's a fiddle of it working
http://jsfiddle.net/gsuy4t27/

Categories

Resources