how to get array values, on input field - javascript

So I have multiple table data insert I want to get input value on some field so I can calculate on another field. How can I do that if that is an array field?
I've tried using javascript but it's only working on first field (not array field).
function tot() {
var txtFirstNumberValue = document.getElementById('price').value;
var txtSecondNumberValue = document.getElementById('qty').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
$(document).ready(function(){
$("#btn-add-form").click(function(){
var addi = parseInt($("#addi-form").val());
var nextform = addi + 1;
$("#insert-form").append("<b>Item Price " + nextform + " :</b>" +
"<input type='text' name='names[]' required>"
"<input id='price' type='text' name='price[]' onkeyup='tot();' required>"
"<input id='qty' type='text' name='qty[]' onkeyup='tot();' required>"
"<input type='text' name='total[]' required>"
$("#addi-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#addi-form").val("1");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btn-add-form">Add</button>
<button type="button" id="btn-reset-form">Reset</button><br><input type="text" name="names[]" required>
<input id="price" type="text" name="price[]" onkeyup="tot();" required>
<input id="qty" type="text" name="qty[]" onkeyup="tot();" required>
<input id="total" type="text" name="total[]" required>
<div id="insert-form"></div>
I expect that way works on added array table but it's not, it only affects field on my first table.

You can not assign the same ID to multiple DOM elements on the same page. I have updated your code a bit to use the item number with the ID. Like, for item 1 ID is price, for item 2 ID is price-2, for item 3 ID is price-3 and so on. Same done with qty and total.
You may try this code:
function sum_total() {
var totalSum = 0;
var calcTotalSum = document.getElementsByClassName("calc-total");
var totalItems = calcTotalSum.length;
var i = 0;
while(i < totalItems) {
if (calcTotalSum[i].value !== "") {
totalSum = totalSum + parseInt(calcTotalSum[i].value);
}
i += 1;
}
if(totalSum > 0) {
console.log("Total Sum is: ", totalSum);
}
}
function tot(event) {
var itemNo = event.target.getAttribute("data-item");
var txtFirstNumberValue = "";
var txtSecondNumberValue = "";
if (itemNo) {
txtFirstNumberValue = document.getElementById('price-' + itemNo).value;
txtSecondNumberValue = document.getElementById('qty-' + itemNo).value;
} else {
txtFirstNumberValue = document.getElementById('price').value;
txtSecondNumberValue = document.getElementById('qty').value;
}
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
if (itemNo) {
document.getElementById('total-' + itemNo).value = result;
} else {
document.getElementById('total').value = result;
}
}
sum_total();
}
$(document).ready(function(){
$("#btn-add-form").click(function(){
var addi = parseInt($("#addi-form").val());
var nextform = addi + 1;
$("#insert-form").append("<b>Item Price " + nextform + " :</b>" +
"<input type='text' name='names[]' required>" +
"<input id='price-" + nextform + "' data-item='" + nextform + "' type='text' name='price[]' onkeyup='tot(event);' required>" +
"<input id='qty-" + nextform + "' data-item='" + nextform + "' type='text' name='qty[]' onkeyup='tot(event);' required>" +
"<input id='total-" + nextform + "' class='calc-total' type='text' name='total[]' required>"
);
$("#addi-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#addi-form").val("1");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btn-add-form">Add</button>
<button type="button" id="btn-reset-form">Reset</button><br>
<input type="hidden" name="addi-form" id="addi-form" value=1 required>
<input type="text" name="names[]" required>
<input id="price" type="text" name="price[]" onkeyup="tot(event);" required>
<input id="qty" type="text" name="qty[]" onkeyup="tot(event);" required>
<input id="total" class="calc-total" type="text" name="total[]" required>
<div id="insert-form"></div>
Hope, it helps you.
EDITED: sum_total function to calculate the sum of the total amount.

I presume that you want to trigger the tot() function on the newly added table rows. For that purpose you need to:
call tot() function to bind to the newly added elements after they have been appended. Or use the jQuery bind method.
Use .class in place of #id attributes on the elemnts so that you can iterate through all of them using the class selector

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;
}
}

Create array from Dynamic table

How can I create an array from this table/form? The onclick function formData() from the dynamic table only returns a concatenated string. I need to create an associative array in JSON using the 'device' variable as key, however I'll settle for any sort of array at all. Clearly, I'm not very good at this...
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementById("form");
//var device = document.getElementById('device').value;
//var j;
var obj = [];
for(j=0; j< cellData.length; j++)
{
obj += cellData[j].value;
}
var json = JSON.stringify(obj);
alert (json);
//document.getElementById('result').innerHTML = json;
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>
1) This my answer how do this on VueJS and jQuery
2) Vanilla js - CODEPEN - DEMO
// Get DOM elements
const $el = [
'#tmpl',
'#user-count',
'#people-count',
'#form-items',
'#btn-add',
'#form',
].reduce((res, item) => {
const method = item.startsWith('#')
? 'querySelector'
: 'querySelectorAll'
const key = item
.replace(/\W/ig, ' ').trim()
.replace(/\s+\w/g, v => v.trim().toUpperCase())
res[key] = document[method](item)
return res
}, {})
// Variable for dynamic template
const tmpl = $el.tmpl.innerHTML.trim()
// Click on Add new button
$el.btnAdd.addEventListener('click', () => {
const peopleCount = +$el.peopleCount.value
const html = Array(peopleCount)
.fill(tmpl)
.join('')
$el.formItems.insertAdjacentHTML('beforeend', html)
})
// Submit form
$el.form.addEventListener('submit', e => {
e.preventDefault()
alert('Submit form by ajax or remove this method for default behavior')
})
// Add form click (it's need for dynamic handler on child elements)
$el.form.addEventListener('click', e => {
// Delete behaviors
if (e.target.classList.contains('btn-del') && confirm('Are you sure?')) {
e.target.closest('.row').remove()
}
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
I have edited your code,
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementsByTagName("tr");
var obj = [];
for(var i=0;i<cellData.length-1;i++){
obj.push(document.getElementById("i"+i).value);
obj.push(document.getElementById("o"+i).value);
}
alert(JSON.stringify(obj));
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>

Javascript query fix

I am new to Javascript programming, can anyone help me on fixing the below script. In this script, I am getting some input from the user and then adding it to an array. Finally displaying it in a table. But for some reason, the last entry in the array overwrites all the previous entries in it.
var CountryList = new Array();
var arrNum = 0;
function initCountry(name, capital) {
this.name = name;
this.capital = capital;
//Comments
//alert(arrNum);
CountryList.push(this);
document.getElementsByName("countryName")[0].value = "";
document.getElementsByName("capitalCity")[0].value = "";
}
function funcSaveButton() {
var txt1 = document.getElementsByName("countryName")[0];
var txt2 = document.getElementsByName("capitalCity")[0];
initCountry(txt1.value, txt2.value);
//alert(txt1.value +":"+ txt2.value);
arrNum++;
}
function displayList() {
var i;
document.write("<table border='2'>");
document.write("<tr> <td> Country Name </td> <td> Capital City </td> </tr>")
for (i = 0; i < CountryList.length; i++) {
//alert("i="+i);
document.write("<tr>");
document.write("<td> " + CountryList[i].name + "</td>");
document.write("<td> " + CountryList[i].capital + "</td>");
document.write("</tr>");
}
document.write("</table>");
}
Country Name: <input type="text" name="countryName" required></input>
<Br> Capital City: <input type="text" name="capitalCity" required></input><br><br>
<input type="button" name="saveButton" value="Save Details!!" onclick="funcSaveButton()"></input>
<input type="button" name="displayButton" value="Display Country List!!" onclick="displayList()"></input>
You are pushing window object to CountryList
inside function this object is window.
use this CountryList.push({name:name,capital:capital});
var CountryList = new Array();
var arrNum = 0;
function initCountry(name, capital)
{
this.name = name;
this.capital = capital;
//Comments
//alert(arrNum);
CountryList.push({name:name,capital:capital});
document.getElementsByName("countryName")[0].value = "";
document.getElementsByName("capitalCity")[0].value = "";
}
function funcSaveButton()
{
var txt1 = document.getElementsByName("countryName")[0];
var txt2 = document.getElementsByName("capitalCity")[0];
initCountry(txt1.value, txt2.value);
//alert(txt1.value +":"+ txt2.value);
arrNum++;
}
function displayList()
{
console.log(CountryList);
var i;
document.write("<table border='2'>");
document.write("<tr> <td> Country Name </td> <td> Capital City </td> </tr>")
for(i=0;i<CountryList.length;i++)
{
//alert("i="+i);
document.write("<tr>");
document.write("<td> "+ CountryList[i].name + "</td>");
document.write("<td> "+ CountryList[i].capital + "</td>");
document.write("</tr>");
}
document.write("</table>");
}
Country Name: <input type="text" name="countryName" required></input><Br>
Capital City: <input type="text" name="capitalCity" required></input><br><br>
<input type="button" name="saveButton" value="Save Details!!" onclick="funcSaveButton()"></input>
<input type="button" name="displayButton" value="Display Country List!!" onclick="displayList()"></input>

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

Categories