write data in some text - javascript

i have following code
<html>
<script type="text/javascript">
function writeit()
{
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
tbox.value = '';
}
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
tbox.value = '';
}
}
</script>
<form name="a_form">
Product name:
<input type="text" id="a_tbox_1" name="a_tbox" value="" />
price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</html>
main idea of program is that i should give me possibilites to write two value product name and price and click after write ii it should write these informations in some text how to do it?please help

function writeit()
{
var strValue = '';
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
//tbox.value = '';
// add:
strValue = 'name: ' + tbox.value;
}
if(strValue != '')
strValue += ', ';
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
//tbox.value = '';
// add:
strValue += 'price: ' + tbox.value + ' € :)';
}
alert(strValue);
// or do whatever you want with it...
}

Your questin is not clear, but try the code below and see if its what you are looking for:
<html>
<head>
<title></title>
<script type="text/javascript">
function writeit() {
var tbox = document.getElementById('a_tbox_1'), tbox2 = document.getElementById('a_tbox_2');
if (tbox.value && tbox2.value){
alert('product = ' + tbox.value + " :: price = " + tbox2.value);
// sendData('action.php?product=' + tbox.value + '&price=' + tbox2.value); (you can send your data via ajax)
tbox.value = '';
tbox2.value = '';
return false;
}
}
</script>
</head>
<body>
<form name="a_form">
Product name: <input type="text" id="a_tbox_1" name="a_tbox" value="" />
Price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</body>
</html>

Related

Don't show the correct value JAVASCRIPT ARRAY

Today I was working to script, when I wanted to test it, I could see that it didn't works correctly it show the value [object Object] and not the real value (It didn't change the value too). It shows: Click here for see the picture
Its necessary click on "Edit" near of Google or Yahoo. I want to show the correct value when I click "Edit" near Google and Edit it when I click edit. I tried to change the value Checked[Item] for Checker[Name] but it only shows undefined.
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = Checker[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.Checker.splice(item, 1, name.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
json:
var Checker = [{
name:"Google",
url: "google.es",
},
{
name:"Yahoo",
url: "yahoo.com",
}
]
Add another input tag for each attribute of Checkers objects.
<input type="text" id="edit-name">
<input type="text" id="edit-url">
And set each input separately
var el = document.getElementById('edit-name');
el.value = Checker[item].name;
var el2 = document.getElementById('edit-url');
el2.value = Checker[item].url;
Working code:
var Checker = [{
name: "Google",
url: "google.es",
},
{
name: "Yahoo",
url: "yahoo.com",
}
]
document.getElementById('edit').style.display = 'none';
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = Checker[item].name;
var el2 = document.getElementById('edit-url');
el2.value = Checker[item].url;
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el2.value;
var name = el.value;
if (url && name) {
Checker[item].name = name;
Checker[item].url = url;
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
<html>
<head>
<title>SSL Checker</title>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-url">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
You are getting correct output with [object Object], because Object.toString() returns exactly [object Object].
To represent your object in a custom format you can change the part of your SSL.Edit() method where you do el.value = Checker[item] to something like
el.value = Checker[item].name; // To show the name
el.value = Checker[item].url; // To show the url
el.value = Checker[item].url + ' ' + Checker[item].url; // To show both

count number of character occurrences in a sentence

I'm writing a code where users can input any text and choose any letter to see how many times it occurred in that particular text - I'm not sure where I'm going wrong
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var count = 0;
for (i = 0; i < length; i++) {
if (parseInt(search) != -1) {
count++;
var search = inputField1.indexOf(inputField2, parseInt(search) + 1);
}
document.getElementId("answer").value = inputField2 + "Occurs" + count + "times";
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Text Occurrences </title>
<h1> Number of Character Occurrences</h1>
<script="text/javascript"> </script>
</head>
<body>
<form>
<p>Enter text: </p>
<p> <input id="inputField1" type="text" /> </p>
<p>Enter any character:</p>
<p> <input id="inputField2" type="text" /> </p>
<input type="button" value="Search" onlick="textOccurrences()" />
</p>
<p>Number of Occurrences:</p>
<p><textarea id="answer"></textarea></p>
</form>
</body>
</html>
Try this as your function.
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var count = inputField1.split(inputField2).length - 1;
document.getElementId("answer").value = inputField2 + "Occurs" + count + "times";
}
You can use a regular expression:
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var re = new RegExp(inputField2, "g");
var count = inputField1.match(re).length;
document.getElementById("answer").value = inputField2 + " Occurs " + count + " times";
}
Note that in your code, you have said getElementId instead of getElementById, also contributing to the error.
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var reg = new RegExp(inputField2,'g');
document.getElementById("answer").value = inputField2 + "Occurs" + inputField1.match(reg).length +
"times";
}
You can try something like this
you can use regex to match any occurence of you chosen letter and then count those matches and you have to syntax errors in your html and javascript
-it is onclick NOT onlick
-and it is getElementById NOT getElementId
here is you code after editing
Javascript
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
console.log("hekasdlkjasd");
var re = new RegExp(inputField2, "g");
var count = inputField1.match(re).length;
document.getElementById("answer").value = inputField2 + " Occurs " + count + " times";
}
Html
<!DOCTYPE html>
<html>
<head>
<title> Text Occurrences </title>
<h1> Number of Character Occurrences</h1>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form>
<p>Enter text: </p>
<p> <input id="inputField1" type="text" /> </p>
<p>Enter any character:</p>
<p> <input id="inputField2" type="text" /> </p>
<input type="button" value="Search" onclick="textOccurrences();" />
</p>
<p>Number of Occurrences:</p>
<p><textarea id="answer"></textarea></p>
</form>
</body>
</html>

Calling multiple functions with code within fails to call both, only calls the first one

Trying to call multiple functions fails.
it only calls the first one, not the second, I mean it has to call both of them.
I use native Javascript then JQuery but still failling.
When I take out the code and just leave the alert("") message, it successfully calls multiple functions. The problem is my functions have to contain codes, not only simple alert statement.
I tried various example from Search but still giving me the same issue which is when I take out the code and leave only the alert message, it works perfect.!!!
<b>Number of items</b> (between 2 and 50):
<input type="number" name="numbItem" min="2" max="50" id="numbItem"> &nbsp&nbsp
<button id='createItem' type="button">Create</button>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
document.getElementById("createItem").onclick = function()
{
var numItems= document.getElementById("numbItem").value;
//alert (price);
//alert (numItems + " items created.")
if (numItems < 2)
{
alert("Can't create just 1 Item;" + "\n" + "Please make sure to enter a number betwen 2 and 50.");
document.body.innerHTML = ""; // Clear Screen
document.location.reload(); // Refresh Page
}
else if (numItems > 50)
{
alert("Can't create more than 50 Items;" + "\n" + "Please make sure to enter a number betwen 2 and 50.");
document.body.innerHTML = ""; // Clear Screen
document.location.reload(); // Refresh Page
}
else
{
alert(numItems + " Items being created. . .");
}
};
</script>
<div id=userForms></div>
<br>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="sumValue" id="sumValueId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Sum" id="btnSumValueId">
&nbsp&nbsp<input type="text" name="sumTaxe" id="sumTaxeId" readonly style="background:#bdf584" size="13"> <input type="submit" value="Sum" id="btnSumTaxeId">
&nbsp&nbsp&nbsp&nbsp<input type="submit" value="Get Totals" id="btnGetTotals" style="width: 140px; position: absolute; left: 550x;">
<br><br>Total Monthly Expenditure&nbsp&nbsp<input type="text" name="totalExpend" id="totalExpValueId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Total" id="btnTotalExpValueId">
<br><br>Effective Tax Rate as %&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="EffectivTaxRate" id="EffectivTaxRateId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Total" id="btnEffectivTaxRateId">
<script type="text/javascript">
$( document ).ready(function()
{
console.log( "ready!" );
$( "#createItem" ).click(function() {
var totalRows = $('#numbItem').val();
var formHtml = '';
for (var i = 1; i <= totalRows; i++)
{
formHtml += ' <input type="text" name="item'+i+'" placeholder="E.g.: Gross Salary" /> <input type="text" name="value'+i+'" placeholder="E.g.: 12000" id="ValueId'+i+'"/> <input type="text" name="tax'+i+'" value="" readonly style="color:#f00;background:#ccc" id="TaxeId'+i+'"> <input type="number" name="vat'+i+'" min="0" max="100" id="VatId'+i+'"> <input name="btnItem'+i+'" value="Calculate" type="button" id="btnCalcId'+i+'"><br><br>';
}
$('#userForms').html(formHtml);
});
});
$('#btnGetTotals').bind('click', function() { student(); });
$('#btnGetTotals').bind('click', function() { calculate(); });
function calculate(){
//alert("Good Morning");
//alert('FRONT !!!');
var total = 10;
for( var i = 3; i <= 50; i++ )
{
var val = parseInt(document.getElementById("ValueId" + i).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("ValueId" + i).value;
if(val>0)
{
total += val;
}
document.getElementById("sumValueId").value = total;
}
}
function student(){
//alert("Hi my name is Sunny");
//alert('FRONT !!!');
var total1 = 55;
for( var i1 = 2; i1 <= 50; i1++ )
{
var val1 = parseInt(document.getElementById("TaxeId" + i1).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("TaxeId" + i1).value;
if(val1>0)
{
total1 += val1;
}
document.getElementById("sumTaxeId").value = total1;
}
}
</script>
</body>
The error is because you cannot use class as a function name.
Convert it to classX or anything else it will work.
Example:
$('#btnGetTotals').bind('click', function() { classX(); });
$('#btnGetTotals').bind('click', function() { student(); });
function classX(){
alert("Good Morning");
}
function student(){
alert("Hi my name is Test");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnGetTotals">
GO
</button>
Update
It is basic to know that you cannot use reserved keywords to name your functions or variables:
See the list of reserved keywords at:
http://www.javascripter.net/faq/reserved.htm
Posting as a new answer because you modified the code after my previous answer:
Several Pointers:
To give spaces use in place of &nbsp
In place of using two bind functions you can call a single one like so:
See below:
$('#btnGetTotals').bind('click', function() {
student();
calculate();
});
You are getting an error in the following code in both of your functions:
for( var i = 3; i <= 50; i++ )
{
var val = parseInt(document.getElementById("ValueId" + i).value);
}
What this does is it iterates from 3 or 2 upto 50 which is wrong as there are not 50 elements if the user selects only 2.
Thus giving you an error:
Cannot read property 'value' of null
So you should enclose your appended code in a common div and then run the loop upto its length like so:
for (var i = 1; i <= totalRows; i++)
{
formHtml += '<div class="newFORM"> <input type="text" name="item'+i+'" placeholder="E.g.: Gross Salary" /> <input type="text" name="value'+i+'" placeholder="E.g.: 12000" id="ValueId'+i+'"/> <input type="text" name="tax'+i+'" value="" readonly style="color:#f00;background:#ccc" id="TaxeId'+i+'"> <input type="number" name="vat'+i+'" min="0" max="100" id="VatId'+i+'"> <input name="btnItem'+i+'" value="Calculate" type="button" id="btnCalcId'+i+'"><br><br></div>';
}
Notice the class newFORM ...
Now whenever I run the loop it should be less than the length of all the classes:
for( var i = 1; i <= $('.newFORM').length; i++ )
{
var val = parseInt(document.getElementById("ValueId" + i).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("ValueId" + i).value;
if(val>0)
{
total += val;
}
document.getElementById("sumValueId").value = total;
}
Hope that helps:
See the demo now:
<p><h3>Budget Calculator TEST [ver 1.0]</h3>**********************************</p>
<b>Number of items</b> (between 2 and 50):
<input type="number" name="numbItem" min="2" max="50" id="numbItem"> &nbsp&nbsp
<button id='createItem' type="button">Create</button>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
document.getElementById("createItem").onclick = function()
{
var numItems= document.getElementById("numbItem").value;
//alert (price);
//alert (numItems + " items created.")
if (numItems < 2)
{
alert("Can't create just 1 Item;" + "\n" + "Please make sure to enter a number betwen 2 and 50.");
document.body.innerHTML = ""; // Clear Screen
document.location.reload(); // Refresh Page
}
else if (numItems > 50)
{
alert("Can't create more than 50 Items;" + "\n" + "Please make sure to enter a number betwen 2 and 50.");
document.body.innerHTML = ""; // Clear Screen
document.location.reload(); // Refresh Page
}
else
{
alert(numItems + " Items being created. . .");
}
};
</script>
<div id=userForms></div>
<br>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="sumValue" id="sumValueId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Sum" id="btnSumValueId">
&nbsp&nbsp<input type="text" name="sumTaxe" id="sumTaxeId" readonly style="background:#bdf584" size="13"> <input type="submit" value="Sum" id="btnSumTaxeId">
&nbsp&nbsp&nbsp&nbsp<input type="submit" value="Get Totals" id="btnGetTotals" style="width: 140px; position: absolute; left: 550x;">
<br><br>Total Monthly Expenditure&nbsp&nbsp<input type="text" name="totalExpend" id="totalExpValueId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Total" id="btnTotalExpValueId">
<br><br>Effective Tax Rate as %&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="EffectivTaxRate" id="EffectivTaxRateId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Total" id="btnEffectivTaxRateId">
<script type="text/javascript">
$( document ).ready(function()
{
console.log( "ready!" );
$( "#createItem" ).click(function() {
var totalRows = $('#numbItem').val();
var formHtml = '';
for (var i = 1; i <= totalRows; i++)
{
formHtml += '<div class="newFORM"> <input type="text" name="item'+i+'" placeholder="E.g.: Gross Salary" /> <input type="text" name="value'+i+'" placeholder="E.g.: 12000" id="ValueId'+i+'"/> <input type="text" name="tax'+i+'" value="" readonly style="color:#f00;background:#ccc" id="TaxeId'+i+'"> <input type="number" name="vat'+i+'" min="0" max="100" id="VatId'+i+'"> <input name="btnItem'+i+'" value="Calculate" type="button" id="btnCalcId'+i+'"><br><br></div>';
}
$('#userForms').html(formHtml);
});
});
$('#btnGetTotals').bind('click', function() { student(); });
$('#btnGetTotals').bind('click', function() { calculate(); });
function calculate(){
alert("Good Morning");
//alert('FRONT !!!');
var total = 10;
for( var i = 1; i <= $('.newFORM').length; i++ )
{
var val = parseInt(document.getElementById("ValueId" + i).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("ValueId" + i).value;
if(val>0)
{
total += val;
}
document.getElementById("sumValueId").value = total;
}
}
function student(){
alert("Hi my name is Sunny");
//alert('FRONT !!!');
var total1 = 55;
for( var i1 = 1; i1 <= $('.newFORM').length; i1++ )
{
var val1 = parseInt(document.getElementById("TaxeId" + i1).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("TaxeId" + i1).value;
if(val1>0)
{
total1 += val1;
}
document.getElementById("sumTaxeId").value = total1;
}
}
</script>

simple addition within array

When the user clicks the button to show all values in the array, how can I get it to add up the total of all 'amounts due'? For example, if one user enters $5, another enters $10 and another enters $25, the total would be displayed as $40.
// Code goes here
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
</body>
</html>
I have changed your code as per your requirement as shown below.Hopefully it will solve your problem
// Code goes here
var customerarray = [];
function displaydata() {
var total=0;
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue+"<br/>";
total+=parseInt(customerarray[i].AmountDue);
}
document.getElementById('output').innerHTML ="User Input Data <br/>" +innerTemphtml;
document.getElementById('total').innerHTML = "Grand Total = "+total;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
<p id="total"></p>
</body>
</html>
There are mutliple things you have to look. I have added a display due() for you.
And here is my js fiddle https://jsfiddle.net/jinspeter/1qxo50uz/
You have to user a number field for Amount. And also addding the amount has to parsed to Int to reject string.
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="number" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<button onClick="displayTotalDue()" class="button" type = "button"> Display Due</button>
<p id="output"></p>
</body>
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function displayTotalDue(){
var total =0;
customerarray.forEach(function(item){
total = total + item.AmountDue
});
var innerTemphtml = 'totalDue=' + total;
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: parseInt(document.getElementById('Amount').value)
});
console.log(customerarray);
}
I try to fix your code. To make it more easy to read. I put the displaydata() method inside of the addtoarray() method, so you can see the results after adding an element in the customers array. Also, I replaced the for with a forEach and added a new div for the total.
I create a node that is a p tag, which will contain the name, id and amount. This tag then will be added to the outputLabel for each element in the array. You can optimize this by just adding the additional node and not running the entire array to print the output.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata() {
outputLabel.innerHTML = '<p>Customers</p>';;
total = 0;
customers.forEach(function(customer) {
var node = document.createElement('p');
node.innerHTML = customer.customerName + ', ' +
customer.customerID + ', ' +
customer.AmountDue;
total += parseInt(customer.AmountDue);
outputLabel.appendChild(node);
});
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
customers.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
displaydata();
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Optimized version: for this version I moved the node (p tag) to the addtoarray() method and I capture the data from the inputs. Then I calculate the total. With this two values a call the displaydata(). This method save time running the array each time you want to print the added element.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata(node, total) {
outputLabel.appendChild(node);
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
var customerName = document.getElementById('custName').value;
var customerID = document.getElementById('CustID').value;
var amountDue = document.getElementById('Amount').value;
customers.push({
customerName: customerName,
customerID: customerID,
amountDue: amountDue
});
var node = document.createElement('p');
node.innerHTML = customerName + ', ' + customerID + ', ' + amountDue;
total += parseInt(amountDue);
displaydata(node, total);
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Set "AmountDue" property of object to number instead of string at .push() call
Number(document.getElementById('Amount').value)
use Array.prototype.reduce() to add two elements of array at a time, return sum
let dues = customerarray.reduce((a, {AmountDue:b}) => a + b, 0);

Collect value of all input with same Class dinamically per milliseconds(setInterval), and wrap it - Using Jquery

I try to build form like this jsfiddle.net/pu3antasyah/5au979ck/ . Collect multiple value from other textarea and input in to one textarea.
Bytheway how to collect all input value dinamically from all input with .step class like this >> <input class="step" /> and wrap it using <li /> . send to <textarea id="collectallfieldtosave texarea" />
$(function(){
var scntDiv = $('#steparea');
var i = $('#steparea p').size() + 1;
$('#addinput').live('click', function() {
$('<p><input class="step-'+ i +'" value="step '+ i +'">remove</p><br/><br/>').appendTo(scntDiv);
i++;
return false;
});
$('.remove').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
window.setInterval(function(){
var
space = ' ',
line = '\n',
summary = $('.summary').val(),
theyield = $('#yield').val(),
IngredientsTitle = '<b>Ingredients for (<span class="yield">' +space+ theyield +'</span>)</b>',
step = '<li>' + $('.step').val() + '</li>';
$('#collectallfieldtosave').val( summary + line + line + IngredientsTitle + line + line + '<ol>' + step + '</ol>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea name="summary" rows="7" class="summary"></textarea>
<br/><br/>
<input id="yield" value="1 person">
<br/><br/>
<div id="steparea">
<p><input class="step" value="step 1">remove</p>
<br/><br/>
</div>
add more step
<br/><br/>
<br/><br/>
<textarea id="collectallfieldtosave" name="nameoffield" rows="15" cols="70" placeholder=".." class="usp-textarea"></textarea>
You shouldn't be using live here. Use on and listen to events on #steparea (live is deprecated) And as of your solution you have to iterate using $.each() jquery fn
$(function(){
var scntDiv = $('#steparea');
var i = $('#steparea p').size() + 1;
$('#addinput').live('click', function() {
$('<p><input class="step" value="step '+ i +'">remove<br/><br/></p>').appendTo(scntDiv);
i++;
return false;
});
$('.remove').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
function findSteps(what){
var acc = '';
$(what).each(function(){
acc += '<li>'+$(this).val()+'</li>';
});
return acc;
}
window.setInterval(function(){
var
space = ' ',
line = '\n',
summary = $('.summary').val(),
theyield = $('#yield').val(),
IngredientsTitle = '<b>Ingredients for (<span class="yield">' +space+ theyield +'</span>)</b>',
step = findSteps('.step');
$('#collectallfieldtosave').val( summary + line + line + IngredientsTitle + line + line + '<ol>' + step + '</ol>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea name="summary" rows="7" class="summary"></textarea>
<br/><br/>
<input id="yield" value="1 person">
<br/><br/>
<div id="steparea">
<p><input class="step" value="step 1">remove<br/><br/> </p>
</div>
add more step
<br/><br/>
<br/><br/>
<textarea id="collectallfieldtosave" name="nameoffield" rows="15" cols="70" placeholder=".." class="usp-textarea"></textarea>

Categories

Resources