Javascript Multiplication Table Based On User Input - javascript

I have a program where the user enters two inputs, and then when the display button is pressed, the multiplication table within the parameters of those two numbers is displayed. However, when I press the button, nothing is displayed.
<span style = "font-size:15px">First Number: </span><input type = "text" id = "first_num" style = "font-size:18px"> <br /><br />
<span style = "font-size:15px">Second Number: </span><input type = "text" id = "second_num" style = "font-size:18px"> <br /><br />
<button type = "button" onclick = "display()">Display</button> <br /><br />
<script type = "text/javascript">
var f_num = document.getElementById("first_num").value;
var s_num = document.getElementById("second_num").value;
function display() {
for (i=1;i<f_num + 1;i++) {
for (j=1;j<s_num + 1;j++) {
if (j == 10) {
document.write(i+"*" +j +"=" +(i*j) + "<br /><br />")
} else {
document.write(i+"*" +j +"=" +(i*j) + " | ")
}
}
}
}
</script>

you should set your variable within the function.in your current code they are being set when the first time script is getting executed and at that time they have blank value.
Correct code will be.
function display() {
var f_num = parseInt(document.getElementById("first_num").value);
var s_num = parseInt(document.getElementById("second_num").value);
for (i=1;i<f_num + 1;i++) {
for (j=1;j<s_num + 1;j++) {
if (j == 10) {
document.write(i+"*" +j +"=" +(i*j) + "<br /><br />");
} else {
document.write(i+"*" +j +"=" +(i*j) + " | ");
}
}
}
}
You can check things on the below plunker.
https://plnkr.co/edit/kgWaEG1ZvgST0RclvV2l?p=preview

Related

how to get the text of an html input generated by javascript?

I'm having a problem I'm using a numeric keypad that I found in codepen this one
https://codepen.io/matthewfortier/pen/ENJjqR
my objective is to store the generated pin in a database but it's a little difficult to do that because I'm taking the generated pin to an input but it looks like this
<input hidden="" id="pin" value="" name="pin">9345</input>
how do i get this generated pin and save it in database
the code is the same as the link
In your html you have this:
<input type="hidden" id="pin" value="9345" name="pin" />
In your Javascript you have this:
let value = document.getElementById('pin').value;
console.log(value);
$(function() {
var container = $(".numpad");
var inputCount = 6;
// Generate the input boxes
// Generates the input container
container.append("<div class='inputBoxes' id='in'></div>");
var inputBoxes = $(".inputBoxes");
inputBoxes.append("<form class='led' class='form-group' action='cadastro.php' method='post'></form>");
var led = $(".led");
// Generates the boxes
for(var i = 1; i < inputCount + 1; i++){
led.append("<input type='password' maxlength=1 class='inp' id='" + i + "' />");
}
led.append("<input type='password' maxlength=12 name='numero' value='93445566' id='numero' />");
led.append("<input type='text' name='te' id='te' placeholder='' />");
led.append("<button id='btn1' type='submit' onclick=''>enviar</button>");
container.append("<div class='numbers' id='inb'><p id='textoo'><span class='bolded'>PIN</span> do serviço MULTICAIXA</p></div>")
var numbers = $(".numbers");
// Generate the numbers
for(var i = 1; i <= 9; i++){
numbers.append("<button class='number' type='button' name='" + i + "' onclick='addNumber(this)'><span class='pin_font'>" + i + "</span></button>");
}
addNumber = function take(field,vall) {
if (!$("#1").val())
{
$("#1").val(field.name).addClass("dot");
}
else if (!$("#2").val())
{
$("#2").val(field.name).addClass("dot");
}
else if (!$("#3").val())
{
$("#3").val(field.name).addClass("dot");
}
else if (!$("#4").val())
{
$("#4").val(field.name).addClass("dot");
}
else if (!$("#5").val())
{
$("#5").val(field.name).addClass("dot");
}
else if (!$("#6").val())
{
$("#6").val(field.name).addClass("dot");
vall = $("#1").val() + $("#2").val() + $("#3").val() + $("#4").val()+ $("#5").val()+ $("#6").val();
document.getElementById("pini").innerHTML = vall;
}
}

innerHtml of a variable does update but returns back

Even though the function deposit() updates the innerHTML it, unfortunately, returns back the constant variable of bal.
var bal = 100;
var currentBalance = document.getElementById("REPLACED")
currentBalance.innerHTML = "Current balance: " + bal + " Pesos"
function deposit() {
var moneygiven = parseInt(document.getElementById("balance").value);
bal += moneygiven
if (moneygiven > 0) {
bal += moneygiven
var output = "Current balance: " + bal + " Pesos";
// Display result
currentBalance.innerHTML = "Current balance: " + bal + " Pesos"
} else {
alert("Error")
}
}
<div>
<p>Code</p>
<h1 id="REPLACED"></h1>
<form>
<input type="number" placeholder="00000" id="balance" name="balanceNumber" />
<button onclick="deposit()" value="" id="btnDeposit">Deposit</button>
</form>
</div>
The default type for button is submit.
You don't want your button to submit your form when clicked, so change it to type="button".
var bal = 100;
var currentBalance = document.getElementById("REPLACED")
currentBalance.innerHTML = "Current balance: " + bal + " Pesos"
function deposit() {
var moneygiven = parseInt(document.getElementById("balance").value);
// bal += moneygiven // not sure if you really want this line of code twice in case of moneygiven > 0
if (moneygiven > 0) {
bal += moneygiven
var output = "Current balance: " + bal + " Pesos";
// Display result
currentBalance.textContent = "Current balance: " + bal + " Pesos"
} else {
alert("Error")
}
}
<div>
<p>Code</p>
<h1 id="REPLACED"></h1>
<form>
<input type="number" placeholder="00000" id="balance" name="balanceNumber" />
<button onclick="deposit()" value="" id="btnDeposit" type="button">Deposit</button>
</form>
</div>
Also, there is no need to work with the unsafe innerHTML property here; use textContent whenever you don't need to inject HTML.

Remove Form Field With Javascript

So I Have Looked Through The Site Only To Not Find The Answer For My Particular Problem. I Am Pretty New To Writing Code And Am Trying To Figure Out How To Remove A Form Field After Its Been Added with Javascript. Here is the code. I would Greatly Appreciate Feedback/Solutions.
var counter = 1;
var limit = 1000;
function addInput(Favorites){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove'>";
document.getElementById(Favorites).appendChild(newdiv);
counter++;
}
function removeInput(newdiv){
document.getElementById('Favorites').removeChild(newdiv);
counter - 1;
}
}
<form>
<div id="Favorites">
Favorite 1<input type="text" name="Favorites[]">
</div>
<input type="button" value="Add New Favorite" onClick="addInput('Favorites');">
<input type = "button" value = "Save Changes">
</form>
there are various issues in your code so I have modified it a bit. So use following js code
var counter = 1;
var limit = 1000;
function addInput(){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <div class='inputElement'>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove' onClick='removeInput(this)'></div>";
document.getElementById("Favorites").appendChild(newdiv);
counter++;
}
}
function removeInput(removeLink){
var inputElement = removeLink.parentNode;
inputElement.remove();
counter= counter - 1;
}
In html you can modify your code a bit
<form>
<div id="Favorites">
<div class='inputElement'>
Favorite 1<input type="text" name="Favorites[]">
</div>
</div>
<input type="button" value="Add New Favorite" onClick="addInput();">
<input type = "button" value = "Save Changes">
</form>
Check out above code here
https://jsbin.com/hizimateri/1/edit?html,js,console,output
If you have any issues with it . Let me know.
Maybe this help? Check the link here link
var counter = 1;
var limit = 2;
function addInput(Favorites) {
if (counter == limit) {
removeInput();
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove'>";
document.getElementById(Favorites).appendChild(newdiv);
counter++;
}
function removeInput() {
var x = document.querySelector('#Favorites div:last-child');
x.remove();
--counter;
}
}

Multiple input fields using JS

Got the following JS code:
<script language="javascript">
fields = 0;
pNR = 0;
err = 0;
function addInput() {
if (fields != 40) {
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
fields += 1;
pNR += 1;
} else {
if (err == 0) {
document.getElementById('text').innerHTML += "<br />Adaugati maxim 40 ingrediente.";
err = 1;
}
document.form.add.disabled = true;
}
}
</script>
and the following HTML:
<input name="name" style="color:#ffffff;" class="name required" type="button" onclick="addInput()" value="Add" />
<div id="text">
</div>
By default, there are no fields. When I press the Add button (fields are added two by two with different names), fill in the fields and click again the Add button, the filled fields are emptied. What did I do wrong?
You aren't simply adding new inputs.
You are:
converting the existing ones to HTML (the value attribute is unchanged, it will still have the default value, not the current value)
adding the HTML for the new inputs to it
generating new DOM elements from that HTML.
Don't use innerHTML. Use createElement, appendChild and friends.
This:
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
Becomes this:
var firstInput = document.createElement("input");
var secondInput = document.createElement("input");
firstInput.type = secondInput.type = "text";
firstInput.name = "first" + pNR;
secondInput.name = "second" + pNR;
var text = document.getElementById("text");
text.appendChild(firstInput);
text.appendChild(secondInput);
text.appendChild(document.createElement("br"));
And, for the else case:
var text = document.getElementById("text");
text.appendChild(document.createElement("br"))
text.appendChild(document.createTextNode("Adaugati maxim 40 ingrediente."));
Working example: http://jsbin.com/OqIWeMum/2/edit

Name and ID changing

I try to build an register form. This register form as text box called "address1" and near it a button called "Add Address". The function of the button - it adds text box for more addresses. the button near the previous address boxes changes to "Remove" which remove the address box and the button. The problem is: I have to set the text boxes in order - 1,2,3,... - I have to change their names and id's. For example - if I remove addressbox number 4 (name, id="address4") then all the next text boxes's names and id's should decrease by 1. I try to do this in for loop. This is hard to explain so I just give you the code. Try in your VS to write for example 'document.getElementById("address"+n).' and you'll see that you even don't see in the list you get that you can write after the dot id or name or value. I realized it is because there is a variable in this is the problem I think. Now here's the code:
<html>
<head>
<title>Untitled Page</title>
<script type="text/javascript">
var n1 = 1; //counting the buttons and divs. doesn't decrease.
//In another words - it counts the number of calls to Add()
var n3 = 1; //counting the address text fields.
//It being reduced and increased so that it will represent the exact number of text fields
function Add() {
n1++;
n3++;
s1 = "<div id='div" + n1 + "'>";
s1 += "Address <input type='text' name='address" + n3 + "' id='address" + n3 + "' />";
s1 += "<input type='button' name='add" + n1 + "' id='add" + n1 + "' value='Add Branch' onclick='Add();' /><br />";
s1 += "</div>";
var n2 = n1 - 1;
document.getElementById('div' + n2).insertAdjacentHTML('afterEnd', s1);
document.getElementById('add' + n2).onclick = function () { Remove(n2, (n3-1)); };
document.getElementById('add' + n2).value = 'Remove';
}
function Remove(nn1, nn2) { //nn1 - div number to remove. nn2 - the address field number in this div
var parent = document.getElementById('barcode');
var child = document.getElementById('div' + nn1);
parent.removeChild(child);
for (nn2 += 1; nn2 <= n3; nn2++) {
var n2 = nn2 - 1; //nn2 - current address text field. n2 - the new number for the address field
document.getElementById('address' + nn2).setAttribute('name', 'address' + n2);
document.getElementById('address' + nn2).setAttribute('id', 'address' + n2);
document.getElementById('address' + n2).setAttribute('value', 'address' + n2);
// try: document.getElementById('address' + nn2).name='address'+n2. doesn't work (for me)
}
n3--;
}
var check = false;
</script>
</head>
<body>
<form name='barcode' id='barcode' action="" >
<div id='div1'>
Address <input type='text' name='address1' id='address1' />
<input type='button' name='add1' id='add1' value='Add Branch' onclick='Add();' /><br />
</div></form>
</body>
</html>
Sorry for the disorder :) I keeped in this code only what linked to the address field and I added comments.
Thanks very much!
edit:
I forgot that you don't see the bug in this code because I already tried to fix it. Before I changed the code it ordered all the divs, text fields and add/remove buttons so all the exsisting items will always be numbered in order (1, 2, 3, ...).
The problem in the following code can be seen if you click 2 times add button, then you remove the first address field and then you click the add button again.
<html>
<head>
<script type="text/javascript">
var n1 = 1;
function Add() {
n1++;
s1 = "<div id='div" + n1 + "'>";
s1 += "Address <input type='text' name='address" + n1 + "' id='address" + n1 + "' />";
s1 += "<input type='button' name='add" + n1 + "' id='add" + n1 + "' value='Add Branch' onclick='Add()' /><br />";
s1 += "</div>";
var n2 = n1 - 1;
document.getElementById('div' + (n2)).insertAdjacentHTML('afterEnd', s1);
document.getElementById('add' + (n2)).onclick = function () { Remove(n2); };
document.getElementById('add' + (n2)).value = 'Remove';
}
function Remove(n) {
var parent = document.getElementById('barcode');
var child = document.getElementById('div' + n);
parent.removeChild(child);
for (n += 1; n <= n1; n++) {
var n2 = n1 - 1;
document.getElementById('add' + n).onclick = function () { Remove(n2); };
document.getElementById('address' + n).setAttribute('name', 'address' + n2);
document.getElementById('add' + n).setAttribute('name', 'add' + n2);
document.getElementById('address' + n).setAttribute('id', 'address' + n2);
document.getElementById('add' + n).setAttribute('id', 'add' + n2);
document.getElementById('div' + n).setAttribute('id','div' + n2);
}
n1--;
document.getElementById('add' + n1).onclick = function () { Add() };
}
</script>
</head>
<body>
<form name='barcode' id='barcode' action="" >
<div id='div1'>
Address <input type='text' name='address1' id='address1' />
<input type='button' name='add1' id='add1' value='Add Branch' onclick='Add();' /><br />
</div>
</form>
</body>
</html>
I think you are working a bit too hard to maintain the order of the addresses and i don't see a general reason to do it (if you have one, please add it to your question).
If you add the inputs with a unique index like you are doing, they will always be different and ordered.
Here's what you can do:
Pass the event caller to the functions Add and Remove and inside you can make the changes you want to those elements.
For example your Remove function (that you would call with Remove(this);) would look like this:
function Remove(callerButton) {
var parent = document.getElementById('barcode');
var child = callerButton.parentNode;
// child is the DIV you want to remove
parent.removeChild(child);
n3--;
}
This way you wouldn't need to do all the sorting you are doing right now.
At the end you can access all the remaining elements with:
var addresses = document.getElementById("barcode").getElementsByTagName("input");
for(var i = 0; i < addresses.length; i++) {
if(addresses[i].type == "text") {
// I'm printing them in the console, you can do with it whatever you like
// If you want to exclude the one with "Add Branch in front of it you can validate for address+n1
console.log("Element.id : " + addresses[i].id + " - Element.value: "+ addresses[i].value );
}
}
I added a jsFiddle with these changes (added a submit button to show the remaining fields in the form).
See if it solves your problem.

Categories