I want to print a multiplication table of user input number. But nothing's happening in the click But what's the mistake? or have I jump into this program early?
<body>
<p>Multiplication table</p>
<input placeholder="Enter the number" type="text" name="number" id="quest"/>
<br />
<button onclick="multFunction()">Process</button>
<br />
<p id="multiply"></p>
<script>
function multFunction() {
var a = document.getElementsById("quest").value;
var i = 1;
for (i = 1 ; i < 11 ; i++) {
var c = parseInt(a) * parseInt(i);
document.getElementById("multiply").innerHTML = a + "x" + i + "=" + c;
}
}
</script>
There's a couple of mistakes in your code:
var a = document.getElementsById("quest").value;
Should be:
var a = document.getElementById("quest").value;
// ^ No "s" there.
Next, you don't want to replace the innerHTML each time, you want to add a new row to it, instead. However, writing to innerHTML that often isn't a good idea. (each write to it causes your browser to re-parse the DOM)
Replace:
document.getElementById("multiply").innerHTML = a + "x" + i + "=" + c;
With:
result += a + " x " + i + " = " + c + '</br>';
And add result = ''; at the front of your function. Then, after the loop, write result to the innerHTML
Here's a working demo:
function multFunction() {
var a = document.getElementById("quest").value;
var i = 1;
var result = '';
for (i = 1 ; i < 11 ; i++) {
var c = parseInt(a) * parseInt(i);
result += a + " x " + i + " = " + c + '</br>';
}
document.getElementById("multiply").innerHTML = result;
}
<p>Multiplication table</p>
<input placeholder="Enter the number" type="text" name="number" id="quest"/>
<br />
<button onclick="multFunction()">Enter the number</button>
<br />
<p id="multiply"></p>
Fix getElementsById at the first line in multFunction() it should be
getElementById
using browser console or plugins like Firebug will make it easier for you to catch such errors
Related
This question already has answers here:
issue with comparing two numbers in javascript
(5 answers)
Closed 1 year ago.
This code is supposed to give you an equation and when you solve it, you get another one in three seconds. You can choose the amount of equations you're getting and how "high" the math is. And it will give you an alert when you did your chosen amount of questions. This code returns no error but it never gives me the alert as it is supposed to. How do I fix this? (I know I am a beginner so my code is a bit messy)
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button() {
text1 = document.getElementById("number").value;
text2 = document.getElementById('questions').value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " +
Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check() {
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if (answer == text11) {
var h = "<input type='number' id='id'> " +
" <button onclick=' check() '> check </button> " +
correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " +
" <button onclick=' check() '> check </button> "
+ correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2) {
alert(correct + '/' + text2);
}
function wait() {
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id='but'> ok </button>
<div id='div'> </div>
Aside from using strict equality, you're also displaying the correct var before updating the value when it's correct. This should work how you want it:
var rand1, rand2, text1, text2
let count = 0;
let correct = 0;
function button() {
text1 = document.getElementById("number").value;
text2 = document.getElementById('questions').value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check() {
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if (answer == text11) {
count = count + 1;
correct = correct + 1;
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count == text2) {
alert(correct + '/' + text2);
}
function wait() {
button()
}
}
<html>
<body>
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id='but'> ok </button>
<div id='div'> </div>
count is an integer and text2 is a string so the if statement comparing count and text2 will never return true. Therefore that block delivering the alert will never fire.
I would simply use javascript's parstInt function to make sure text2 is an integer
text2 = parseInt(document.getElementById('questions').value);
So I'm currently taking a coding class and am not very well versed in coding. I'm having trouble with a getelementbyid block which isn't writing my looped array for an assignment. Could anyone help me out?
Here's the code:
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById(message).innerHTML = "your name is " + input[n] + "<br>"
document.getElementById(message2).innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
Your variables and your id-s have the same names. By doing getElementbyId(message) you are passing the variables' values instead of the fixed id you gave to your elements.
You need to put the id-s in quotes as follows:
document.getElementById("message")
document.getElementById("message2")
Tested at my end and this is working code
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById('message').innerHTML = "your name is " + input[n] + "<br>"
document.getElementById('message2').innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
error:-
The id of getElementbyId must be in quotes
Make sure your selectors are strings
document.getElementById("message"); not document.getElementById(message);
Make sure you end your lines of code with semi-colons. This is not optional even though the code will attempt to run without them.
Change your output to render your accumulated data - right now you're overwriting your output every time you loop.
Note: I don't know what you're doing with the numerical value inside of the prompt methods (names and grade ) so I didn't touch it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = [];
var message = " ";
var message2 = " ";
var n = 0;
var i = 1;
var names = n;
var grade = i;
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name " + names)
message += "Your name is " + input[n] + "<br>";
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value) " + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>";
}
document.getElementById("message").innerHTML = message + "<br>";
document.getElementById("message2").innerHTML = message2 + "<br>";
</script>
#SlavicMilk
Below should be sufficient for your assignment:
HTML (index.html):
<h1 style="text-align: center">Name and Grades</h1>
<table>
<thead>
<th>Name</th>
<th>Grade</th>
</thead>
<tbody id="data">
</tbody>
</table>
<script src="script.js"></script>
JS (script.js):
let student = []
for (let i = 0; i < 5; i++) {
student[i] = {
"name": window.prompt(`Enter Name ${i + 1}`),
"grade": window.prompt(`Enter Grade (numerical value) ${i + 1}`)
}
}
document.getElementById('data').innerHTML = student.map(student => {
return `<tr><td>${student.name}</td><td>${student.grade}</td></tr>`
})
First I created a version of this which worked where I didn't input the value on the webpage:
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == 3)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
</script>
Then this is the version I'm trying to create where I enter in the input on the webpage, and then the computer tries to guess it, but it's not executing at all or showing anything when I try to debug in the console.
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
document.getElementById("fingersSubmit").onclick = function ()
{
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == numberOfFingers)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
}
I'm a beginner coder so if there is any useful knowledge pertaining to this in addition to showing me the correct code, then I'd greatly appreciate that!
Thanks!
Here's a working version where I tried to stay as close to your original code as possible:
<html>
<body>
<p>Enter in how many fingers (between 0 and 5) you are holding up:</p>
<p>
<input id="fingersInput" type="text" />
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
document.getElementById('fingersSubmit').onclick = function() {
i = 0;
var fingersText = '';
var correctGuesses = 0;
var numberOfFingers = document.getElementById('fingersInput').value;
while (i < 5) {
var computerGuess = Math.floor(Math.random() * 5 + 1);
fingersText += '<p>' + computerGuess + '</p>';
if (computerGuess == numberOfFingers) {
correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById('fingers-game-v2').innerHTML = fingersText;
document.getElementById('computer-guess-results').innerHTML =
'<h3>' +
'Number of times the computer guessed correctly: ' +
'</h3>' +
correctGuesses;
};
</script>
</body>
</html>
The main reason your code wasnt working is because you need to get the input value when the button is clicked (i.e. place it inside the onclick)
The other issue is that you redeclare correctGuesses inside the if block, so you should just remove the var keyword, otherwise you will get NaN
Finally, this isn't strictly a problem with your code, but moving forward you should be aware that numberOfFingers is a string whereas correctGuesses is a number. In your if block, you compare the two values and it works because you used ==, which only checks value. It's typically better practice to use === which is a stricter equality check, comparing both value and type. So moving forward, you might want to make sure to convert numberOfFingers to a number before you do the equality check
I have a textarea, where the user can write his name.
<h2><textarea name="txt_company" rows="5" id="company_text"></textarea><textarea name="txt_visitor" rows="5" id="visitor_text">
</textarea><textarea name="text_rp" rows="5" id="rp_text">
</textarea></h2>
When pressing the button
<input type="submit" class="wmfg_btn" name="submit_form" id="submit_form_btn" value="Code generieren..." onclick="generatecode();" />
the output with the entered name will be displayed as an alert:
function generatecode() {
var text_company = document.getElementById("text_company").value;
var text_visitor = document.getElementById("text_visitor").value;
var text_rp = document.getElementById("text_rp").value;
alert('Blablabla' + text_company + 'blablabla' + text_visitor + 'blablabla' + text_rp + 'blabla.');
}
Now, my problem is, that if the user puts in for example 2 names with a line break between, my output should be expanded with <br> after each variable.
Like for example:
alert('Blablabla' + text_company + '**ADDITION**blablabla' + text_visitor + 'blablabla' + text_rp + 'blabla.')
But im stuck right now, I cant find a good solution...
Im open for any advice!
you could try to add \n as a line break for the entry.
function generatecode() {
var text_company = document.getElementById("text_company").value + " \n"; // added line break
var text_visitor = document.getElementById("text_visitor").value + " \n"; // added line break
var text_rp = document.getElementById("text_rp").value + " \n"; // added line break
alert('Blablabla' + text_company + 'blablabla' + text_visitor + 'blablabla' + text_rp + 'blabla.');
}
EDIT: Added \n to all "text_' variables
You can use the method indexOf to detect if the value of the textarea contains "\n" and according to the result (-1 if no line break) you can add or not a line break to the value of the textarea.
<textarea name="test" rows="5" id="test"></textarea>
<input type="button" onclick="alertValue()" />
<script>
function alertValue(){
var test = document.getElementById("test").value;
if(test.indexOf("\n") != -1){
test += "\n";
}
}
</script>
In addition, take care of your textearea ids: text_company != company_text.
What i am trying to achieve is adding the javascript loops and the named variables into an sql database, some of them are already added to an external script so work fine however some which i have named in the SQL script at the bottom still need adding, however as the database won't accept a colon ":" they won't enter it and is returning an error, looking at the code at the bottom with replace function im sure you can see what i am trying to achieve but failing miserably, help is much appreciated!
window.status = 'Loading contingency scripts - please wait...';
audit('Loading contingency scripts');
var conting = {
i: 0,
start: function() {
window.status = 'Loading form - please wait...';
var t = '';
t += '<form name="frm_conting" id="frm_conting" onsubmit="return false;">';
t += '<table width="100%" cellspacing="1" cellpadding="0">';
t += '<tr><td>Date (DD/MM/YY):</td><td><input type="text" size="8" value="' + current_date + '" id="date"></td></tr>';
t += '<tr><td>Time Started:</td><td><select id="timefrom"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select></td></tr>';
t += '<tr><td>Time Finished:</td><td><select id="timeto"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select><tr><td>Extension #:</td><td><input type="text" size="5" value="' + my.extension + '" id="staffid"></td></tr>';
t += '<tr><td>Desk ID:</td><td><input type="text" size="5" value=' + my.deskid + ' id="desk"></td></tr>';
t += '<tr><td>Number of calls:</td><td><input type="text" size="5" id="calls"></td></tr>';
t += '<tr><td>Avid ID:</td><td><input type="text" size="5" id="avid"></td></tr>';
t += '<tr><td><input type="button" value="Submit" onClick="conting.save()"></td>';
t += '</table>';
t += '</form>';
div_form.innerHTML = t;
window.resizeTo(400, 385);
window.status = '';
},
save: function() {
var conting_date = frm_conting.date.value;
if (!isdate(conting_date)) {
alert("You have entered an incorrect date.");
return false;
};
var conting_timefrom = frm_conting.timefrom.value;
var conting_timeto = frm_conting.timeto.value;
if (conting_timefrom == '' || conting_timeto == '') {
alert("You need to enter a starting & finishing time.");
return false;
};
if (conting_timefrom > conting_timeto) {
alert("The time you have entered is after the finish time.");
return false;
};
var conting_staffid = frm_conting.staffid.value;
if (conting_staffid.length != 5) {
alert("You have entered an incorrect extension number.");
return false;
};
var conting_desk = frm_conting.desk.value;
if (conting_desk.length != 5) {
alert("You have entered an incorrect desk ID.");
return false;
};
var conting_calls = frm_conting.calls.value;
if (isNaN(conting_calls)) {
alert("You have not entered amount of calls.");
return false;
};
var conting_avid = frm_conting.avid.value;
if (isNaN(conting_avid)) {
alert("You have entered an incorrect avid ID.");
return false;
};
if (conting_avid.length != 5) {
alert("You have entered an incorrect avid ID.");
return false;
};
conn.open(db["contingency"]);
rs.open("SELECT MAX(prac_id) FROM practice", conn);
var prac_id = rs.fields(0).value + 1;
var prac_timefrom = parseFloat(frm_conting.timefrom.value);
var prac_timeto = parseFloat(frm_conting.timefrom.value);
var prac_calls = frm_conting.calls.value;
var prac_avid = frm_conting.avid.value;
rs.close();
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
conn.close();
}
};
window.status = '';
This bit of code looks extremely dubious.
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
you should use parameterised queries to avoid SQL injection. Additionally even without any deliberate SQL injection attempts this code will fail if any of the form fields contain the ' character.
You are assigning to the variable q twice and aren't executing the result of the first assignment. (And declaring it twice actually?!)
There is no syntax such as UPDATE SELECT it would need to be something like UPDATE practice SET SomeColumn = REPLACE (SomeColumn, 'isNaN', 'isNull') presumably except see 4 and 5.
I'm not clear what the Replace is meant to be doing anyway. What are the 3 parameters you have given it?
It would be better to do the Replace on the value before inserting into the database rather than inserting it wrong then updating it to the new value.