JDS JDS - 3 years ago 163
HTML Question

Grabbing value of input to string

I am completing a project which contains the following code. All that needs to be fixed is the start of each line. For example, if I used the input "8" it wouldn't reveal the full line of working, instead each line starts with a multiplication sign. Same goes for the other side which has bullet points. I wish to keep the bullet points but also have my input value on each line. I have tried using an id for my value, but it was unsuccessful.

Any advice or assistance would be greatly appreciated,

Cheers.

<html>
<head>
</head>
<body>

<h2 style="color:blue;">Enter an integer from 1 to 9:</h2>

<input type="text" id="multipleOf" value="">

<button onclick="multiplier()">Generate Times Table</button>

<div style="color:blue;" id="multTable"> <h2>Multiplication Table</h2> </div>

<script type="text/javascript">
//<![CDATA[
function multiplier() {
var mult = document.getElementById('multipleOf').value;
var str = '<table border="0" width="100%"><tr><td>';
str += '';
str += '';
for (var i=1; i<10; i++) {
str += '<br />';
str += '' + ' x ' + i + ' = ';
str += mult * i;
str += '';
str += '';
}
str += '</td><td>';
for (var i=1; i<10; i++) {
str += '<br />';
str += '&bull;' + ' x ' + i + ' = ';
str += mult * i;
str += '';
str += '';
}
str += ''
str += '</td></tr></table>';
document.getElementById('multTable').innerHTML = '<h2>Multiplication
Table</h2>'+str;
}
//]]>

</script>

</body>
</html>

Answer Source

mult already contains the first operand, so it just needs to be added to str in the loops:

for (var i = 1; i < 10; i++) {
    str += "<br />";
    str += mult + " x " + i + " = "; // Concatenating mult here.
    str += mult * i;
    str += "";
    str += "";
}

for (var i = 1; i < 10; i++) {
    str += "<br />";
    str += mult + "&bull;" + " x " + i + " = "; // Concatenating mult here.
    str += mult * i;
    str += "";
    str += "";
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download