How to place a variable inside getElementbyId() that changes during each repetition of a loop? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want something similar to f" {variable} " of python
Ive tried
function press()
{
for(var i=0; i<4; i++)
{
if(!document.getElementById('ip'+i).value)
{
alert("error");
break;
}
}
but it didnt work.

I want something similar to f" {variable} " of python
template strings ${variable}
In JavaScript you can use template strings
The usage is
` ${variable} `
document.getElementById('btn').addEventListener('click', press)
function press() {
for (var i = 0; i < 4; i++) {
if (!document.getElementById(`ip${i}`).value) {
alert("error");
break;
}
}
}
<input id="ip0"/>
<input id="ip1"/>
<input id="ip2"/>
<input id="ip3"/>
<button id="btn">Click</button>

Related

Math.evaluate is not a function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
im trying to do some Math in a js function while using MathJs & getting this error :Math.evaluate is not a function
<script src=" https://cdnjs.com/libraries/mathjs"></script>
Do-Math :<input id="formula" />
<button onclick="goCalc()">Go</button>
results:<input id="resTxt"/>
<script type="text/javascript">
function goCalc() {
let Mformula = $("#formula").val();//the formula im trying to get =6*4+2^2
var res = document.getElementById("resTxt");
// res.setAttribute("value", Mformula);
var mat = Math.evaluate(Mformula);
res.setAttribute(mat);
console.log(mat);
}
It looks like you might be experiencing multiple problems based on the code you've shown. It's not exactly clear which are true issues and which might be related to typos, etc. so here's a complete example demonstrating how to include the library as well as evaluating the text value of an input element each time it changes, writing the result to another element:
body { font-family: sans-serif; } #expression, #result { font-family: monospace; font-size: 1rem; } #expression { padding: 0.5rem; }
<label>Expression: <input id="expression" value="6 * 4 + 2 ^ 2" /></label>
<pre><code id="result"></code></pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.0.1/math.min.js" integrity="sha512-B82WLflI1EQiR9sGbIV1ddGVvK4ghj1xjMShL7YvcOrHjX2qP72lHztT1DxBVPiz1aTR6mOUJbtwj06uadL2GA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="module">
const input = document.getElementById('expression');
const output = document.getElementById('result');
function evaluate () {
const expression = input.value.trim();
let result;
try {
result = math.evaluate(expression);
}
catch (ex) {
if (ex instanceof Error) result = ex.toString();
else throw ex;
}
output.textContent = result;
}
input.addEventListener('input', evaluate);
evaluate();
</script>

Wrap words with &nbsp in span [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 4 years ago.
Improve this question
I need wrap words with &nbsp in span, for example:
<p>Word word and word2? But word word to.</p>
Should become:
<p>Word <span>word and word2?</span> But word <span>word to.</span></p>
I wanna do this with regular expression in JavaScript.
You can do something like this https://regex101.com/r/bUflp4/2 for you regex. Be care however, it won't accept tag inside others.
For the replacement, you can use something like this
var elements = document.getElementsByClassName("text-to-replace");
for (var i = 0; i < elements.length; i++) {
var innerHTML = elements.item(i).innerHTML;
var regex = new RegExp('([^ ,<]* [^ ,<\/]*)', 'ig');
var text = innerHTML.replace(regex, '<span class="span-to-add">$1</span>');
elements.item(i).innerHTML = text;
}
.span-to-add {
background-color: yellow;
}
<div class="container">
<p class="text-to-replace">Word word and word2? But word word to.</p>
<p class="text-to-replace"> word this is an example</p>
<p class="text-to-replace">this is another example</p>
</div>

Need Help: Make the quiz random [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 8 years ago.
Improve this question
I'm having trouble making the questions random. If you could help, it would be awesome!
(If you have spear time; I've been given the task to mark correct answer with a green feather and wrong answers with red feather, for instance, if you get 3 correct and 2 wrong. It will show 3 green feathers and 2 red feathers as score.) Thank you!
<script type="text/javascript">
var questions = [
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'],
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'] // Note: no comma after last entry
];
var qNo = 0;
var correct = 0;
var cnt = 0;
function NextQuestion(response) {
if ((qNo < questions.length) && (response == questions[qNo][1])) {
correct++;
}
document.getElementById('score').innerHTML = 'Correct ' + correct + ' of 6 questions';
qNo++;
if (qNo < questions.length) {
document.getElementById('Pic').src = questions[qNo][0];
cnt++;
}else{
alert('Quiz is done. You got ' + correct + ' points!');
}
}
onload = function() {
document.getElementById('Pic').src = questions[0][0];
}
</script>
</head>
<body>
<div align="center">
<h1>Which car is it?</h1>
<img src="" id="Pic" height="200" width="250">
<p>Is it
<button onclick="NextQuestion('0')">Red</button>
<button onclick="NextQuestion('1')">Black</button>
<button onclick="NextQuestion('2')">Yellow</button>
<p>Your score: <br>
<span id="score"></span>
</div>
</body>
</html>
Well, your questions are in an array. So what you should be researching is how to randomise the order of an array.
questions.sort(function() { return Math.floor(Math.random() * 2); });

Hide <br /> tag from textarea [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
<script type='text/javascript'>
function replaceNewlines(e) {
var element = document.getElementById('myTextarea');
if (e.keyCode == 13) {
element.value = element.value.replace("\r", "<br />");
element.value += "___NEWLINE___\n";
element.value = element.value.replace("___NEWLINE___\n", "<br />");
}
}
</script>
This code works fine but when I press enter, <br /> appears in the textarea and I don't want to appear this in my textarea.
Can somebody help me?
So, how about replacing <br /> with a new line?
<script type='text/javascript'>
function replaceNewlines(e) {
var element = document.getElementById('myTextarea');
element.value = element.value.replace(/<br\s*\/?>/g, '\n');
}
</script>
See http://jsfiddle.net/tkR9S/ for a full demo.

javascript split string by pattern [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
i want to split this string in JavaScript.
i try it:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "<new_a><new_b><sb_c>";
var res = str.split("<");
document.getElementById("demo").innerHTML=res;
}
</script>
</body>
</html>
result:
new_a> , new_b> , sb_c>
i want to my result : new_a , new_b , sb_c
how can i do?
function myFunction()
{
var str = "<new_a><new_b><sb_c>";
str = str.replace("<","");
str = str.replace(">"," ");
var res = str.split(" ");
document.getElementById("demo").innerHTML=res;
}
Try this code.

Categories