i have a javascript function which has foor loop in it. once the loop exists it is not displaying alert can anyone suggest what might be wrong.
the code is below
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<?PHP Include('Includes\common\header_items.php');
session_start();
?>
</head>
<body>
<form name="step2" method="POST">
<div id="qwe">
<table width="500px" id="myTable" name="myTable">
<thead>
<tr>
<td >Brawing / Document No.</th>
<td>Revision No.</th>
<td>Description (Optional)</th>
</tr>
</thead>
<tbody>
<tr>
<td width="40%"><input type="text" id="553" name="2" /></th>
<td width="10%"><input type="text" id="revID553" name="3" /></th>
<td width="45%"><input type="text" id="descpID553" name="4" /></th>
</tr>
<tr>
<td width="40%"><input type="text" id="4" name="21" /></th>
<td width="10%"><input type="text" id="15" name="31" /></th>
<td width="45%"><input type="text" id="6" name="41" /></th>
</tr>
<tr>
<td width="40%"><input type="text" id="556" name="2" /></th>
<td width="10%"><input type="text" id="revID556" name="3" /></th>
<td width="45%"><input type="text" id="descpID556" name="4" /></th>
</tr>
</tbody>
</table>
<input type="submit" onclick='Javascript: return testFunc();'>
</div>
</form>
<script language="javascript">
var table_row = [];
function testFunc(){
table_row.length = 0;
var count = 0;
var testing = document.getElementById("myTable").getElementsByTagName("input");
for (i=0; i<=testing.length; i++){
var data = document.getElementById("myTable").getElementsByTagName("input")[i].id;
if(data.substring(0,2) == "55")
{
var value_doc = document.getElementById("myTable").getElementsByTagName("input")[i].value;
var value_rev = 'revID'+data;
var rev = document.getElementById(value_rev).value;
var value_descp = 'descpID'+data;
var descp_data = document.getElementById(value_descp).value;
//code to add into array
table_row[count] = [data,rev,descp_data];
count ++;
}
}
alert("I am in the end");
</script>
</body>
</html>
i cant figure out why it is not displaying the last alert. Any suggestions? THe last alert is not working.
Hello Your code is working fine for me.
Write your function like this.
function testFunc(){
alert("I am in test function");
for (i=0; i<=5; i++){
//code to add values in array
// it displays the values added in array correctly
alert('call');
}
alert("Function is Ending"); //this is not displayed once loop runs 5 times.
return true;
}
Now Call your function in load.
$(document).ready(function () {
testFunc();
});
Fiddle Demo
You have not call your function :
JSFiddle
Check Below Code :
function testFunc(){
alert("I am in test function");
for (i=0; i<=5; i++){
//code to add values in array
// it displays the values added in array correctly
}
alert("Function is Ending"); //this is not displayed once loop runs 5 times.
return true;
}
testFunc(); // calling function
The main problem is in extra loop iteration.
I also rewrite code a little bit to avoid many document.getElementById("myTable").getElementsByTagName("input"), because it causes searching over DOM every time it appears.
<script language="javascript">
var table_row = [];
function testFunc() {
table_row.length = 0;
var count = 0;
var testing = document.getElementById("myTable").getElementsByTagName("input");
for (i = 0; i < testing.length; i++) {
var data = testing[i].id;
if (data.substring(0,2) == "55") {
var value_doc = testing[i].value;
var value_rev = 'revID' + data;
var rev = document.getElementById(value_rev).value;
var value_descp = 'descpID' + data;
var descp_data = document.getElementById(value_descp).value;
//code to add into array
table_row[count] = [data, rev, descp_data];
count ++;
}
}
alert("I am in the end");
}
</script>
Related
I just can't see what am I doing wrong... It doesn't calculate the "stunden" field.
There is some small mistake from my side and I just can't see it.
EDITED: now all is working as it should
$(document).ready(function(){
$('.item').keyup(function(){
var starts = 0;
var ends = 0;
var stunden = 0;
if (!isNaN($(this).find(".starts").val())) {
starts = $(this).find(".starts").val();
}
if (!isNaN($(this).find(".ends").val())) {
ends = $(this).find(".ends").val();
}
stunden = ends - starts;
$(this).find(".stunden").val(stunden);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table id="t1" class="table table-hover">
<tr>
<th class="text-center">Start Time</th>
<th class="text-center">End Time</th>
<th class="text-center">Stunden</th>
</tr>
<tr id="row1" class="item">
<td><input name="starts[]" class="starts form-control" ></td>
<td><input name="ends[]" class="ends form-control" ></td>
<td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td>
</tr>
<tr id="row2" class="item">
<td><input name="starts[]" class="starts form-control" ></td>
<td><input name="ends[]" class="ends form-control" ></td>
<td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td>
</tr>
</table>
</div>
The problem is that you are recalculating when a key is pressed in the .stunden fields, so you should move the event to the other inputs, or the parent row. You'll need something like this.
$('.item').keyup(function(){
var starts = 0;
var ends = 0;
var stunden = 0;
if (!isNaN($(this).find(".starts").val())) {
starts = $(this).find(".starts").val();
}
if (!isNaN($(this).find(".ends").val())) {
ends = $(this).find(".ends").val();
}
stunden = starts - ends;
$(this).find(".stunden").val(stunden);
});
Let me try your original keyup code .ends ,I just want to explain how is work below code
call .starts ,we currently in tr>td>input ,so need backup to tr by parent() then we find .starts inside its elements.As also .ends
find .studen is also in state tr>td>input ,so backup to td and go next td by next() then find .studen .
$(document).ready(function(){
$('.ends').keyup(function(){
var starts = 0;
var ends = 0;
var stunden = 0;
if (!isNaN($(this).parent().parent().find(".starts").val())) {
starts = $(this).parent().parent().find(".starts").val();
}
if (!isNaN($(this).parent().parent().find(".ends").val())) {
ends = $(this).parent().parent().find(".ends").val();
}
stunden = starts - ends;
$(this).parent().next().find('.stunden').val(stunden);
});
});
I am am trying to read json data and import it to my table in html.
But some how it is not working.
I have already implemented a function to type in data what works great.
Only the function to load the json data is not working.
But i really don't know why.
I have posted the whole html code and my load data function.
MY Javascript code:
function loadData() {
var text = '{"employees":[' +
'{"firstName":"Ben","lastName":"dsafsad" },' +
'{"firstName":"Peter","lastName":"dsdsaadsj" },' +
'{"firstName":"Jules","lastName":"MIAU" }]}';
obj = JSON.parse(text);
for (var i = 0; i < obj.length; i++) {
var currentObj = obj[i];
var myName = currentObj.employees[0].firstName;
var age = currentObj.employees[0].lastName;
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
}
}
MY HTML code:
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" id="age">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()">
<input type="button" id="add" value="Load Data" onclick="Javascript:loadData()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</div>
<div id="mydata">
<b>Current data in the system ...</b>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Name</b></td>
<td><b>Age</b></td>
</tr>
</table>
<br/>
</div>
</body>
</html>
You should be iterating over obj.employees, not obj. You have one object, which is composed of an employees array (with length of 3 in your example).
obj = JSON.parse(text);
console.log(obj);
console.log(obj.length); //this returns undefined
console.log(obj.employees.length); //this is what you want
for (var i = 0; i < obj.employees.length; i++) {
var currentObj = obj.employees[i];
console.log(currentObj);
var myName = currentObj.firstName;
console.log(myName);
var age = currentObj.lastName;
console.log(age);
}
Fiddle demo
You also have a problem here:
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
myName and age are variables you defined, not html elements, and as such, they don't have a value property. You just need to refer to the variables themselves, like so:
row.insertCell(1).innerHTML= myName;
row.insertCell(2).innerHTML= age;
Update Fiddle Demo
I make a code , that randomly display an 6-item array in a div.
i want to read the array and pass it to function to calculate the mean of it?
HTML
what i must do , how can i store the data of div(id="numbers" )
and push it in array ?
<pre>
<div >
<form action="" method="post" name="meanForm" onsubmit='return false' id="formmine">
<table width="100%" border="0"
<tr>
<td colspan="3" style="background-color:#06F ;color:#FFF">Answer this problem</td>
</tr>
<tr>
<td style="color:green; font-size:20px">What is the mean of these numbers </td>
<td colspan="2" ><div id="numbers"></div>
</td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr id="answerANDpic">
<td height="62" colspan="3" align="center" > <input name="" type="text" size="15" maxlength="100" height="50" style=" border: solid #0C0 ; border-width:thin" id="answer" onkeydown="searchm(this)"/> </td>
</tr>
<tr>
<td colspan="3" ><div id ="explain" ></div></td>
</tr>
<tr>
<td> </td>
<td><input name="" type="button" id="newEx" style="background-color:green ; color:white" align ="left" value="New Problem" class="send_feed" onclick="randomArray(6,0,99)" /></td>
<td><input name="" type="button" id="solution" style="background-color:#606 ; color:#FFF " align="left" class="send_feed" value="Solution" onclick="solution()"/></td>
</tr>
</table>
</form>
</div>
in JS
var myNumArray = randomArray(6,0,99);
function random_number(min,max) {
return (Math.round((max-min) * Math.random() + min));
}
function randomArray(num_elements,min,max) {
var nums = new Array;
for (var element=0; element<num_elements; element++) {
nums[element] = random_number(min,max);
}
document.getElementById("numbers").innerHTML=nums;
calcMean(nums);
}
function calcMean(nums) {
var num=0;
for (var i=0;i<nums.length;i++) {
num += parseFloat( nums[i], 6 );
}
var divide=num/nums.length;
var mean=(parseInt(divide,10));
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
return mean,maxi,mini;
}
function searchm(ele) {
if(event.keyCode == 13) {
// alert(ele.value); // i get the value and put it on alert
var inans= ele.value;
return inans;
}
}
function soltuion(){
//read array saved in div id="numbers"
// call calcMean()
//get the mean and max min values
}
See comments in code below. Your code is not far off working.
function calcMean(nums){
var num=0;
for (var i=0;i<nums.length;i++){
// parseFloat only has one argument
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
num += parseFloat( nums[i])
// If the numbers in the nums array
// are already floats, you don't need parseFloat
// So maybe you can do... ?
// num += nums[i]
}
// The line below might divide by zero, so check
if (nums.length == 0) {
return 0;
}
var divide=num/nums.length;
// No need to reparse a number.
mean=divide
// This code suggests that nums is already filled with numbers
// See comment in for-loop above
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
// This returns all 3 numbers
return [mean,mini,maxi];
// If you want just the mean,
// return mean;
}
I have a checkbox list of items. I want everytime I check items, to be able to display the price of the item and the sales tax for it, sum a subtotal of each value (price and tax) and sum the total cost. This is what I've done so far (the code is a mix from scripts I' ve found online):
<html>
<head>
<title>List</title>
<SCRIPT>
function UpdateCost() {
var sum = 0;
var gn, elem;
for (i=1; i<3; i++) {
gn = 'item'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value);
}
}
document.getElementById('totalcost').value = sum.toFixed(2);
}
</SCRIPT>
</head>
<body>
<FORM >
<table border="1px" align="center">
<tr>
<td>List of Items
<td>Price
<td>Tax
</tr>
<tr>
<td><input type="checkbox" id='item1' value="10.00" onclick="UpdateCost()">item1
<td><INPUT TYPE="text" id='price1' SIZE=5 value="">
<td><INPUT TYPE="text" id='tax1' SIZE=5 value="">
</tr>
<tr>
<td><input type="checkbox" id='item2' value="15.00" onclick="UpdateCost()">item2
<td><INPUT TYPE="text" id='price2' SIZE=5 value="">
<td><INPUT TYPE="text" id='tax2' SIZE=5 value="">
</tr>
<TR>
<TD>Subtotals
<TD><INPUT TYPE="text" id="subtotal1" value="" SIZE=5>
<TD><INPUT TYPE="text" id="subtotal2" value="" SIZE=5>
</TR>
<tr>
<td>Total Cost:
<td><input type="text" id="totalcost" value="" SIZE=5>
<td><input type="reset" value="Reset">
</tr>
</table>
</FORM>
</body>
</html>
Here is a working implementation using Knockout.js. The fiddle is here: http://jsfiddle.net/pJ5Z7/.
The ViewModel and Item functions define your data structure and logic. Bindings to properties in the view-model are done in the HTML and Knockout will update those dynamically. These are two-way: I left the price values as inputs to illustrate this. If you check an item and change its price, you will see that change reflected in the rest of the model and view (after the input loses focus).
This approach allows for clean separation of concerns and much more maintainable code. Declarative bindings in Knockout and similar libraries help you avoid manual DOM manipulation as well.
If you want to change your dataset, all you have to do is add or remove items in the initialization code:
var items = [
new Item('item1', 10.00),
new Item('item2', 15.00)
];
With the old approach, you would have had to update the DOM as well as all of your logic. This data could even be loaded dynamically from a web service or anywhere else.
I also cleaned up the markup a bit and moved the size definition of input elements to CSS. It's better practice to define styles there.
If you want to learn more, just go to the Knockout website. There are a number of helpful demonstrations and tutorials.
JavaScript
//Main viewModel
function ViewModel(items) {
var self = this;
self.items = ko.observableArray(items);
self.priceSubtotal = ko.computed(function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
//Only add up selected items
items[i].selected() && (sum += parseFloat(items[i].price()));
}
return sum.toFixed(2);
});
self.taxSubtotal = ko.computed(function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
//Only add up selected items
items[i].selected() && (sum += parseFloat(items[i].taxAmount()));
}
return sum.toFixed(2);
});
self.totalCost = ko.computed(function() {
return (parseFloat(self.priceSubtotal()) + parseFloat(self.taxSubtotal())).toFixed(2);
});
//Functions
self.reset = function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
items[i].selected(false);
}
};
}
//Individual items
function Item(name, price) {
var self = this;
self.name = ko.observable(name);
self.price = ko.observable(price);
self.selected = ko.observable(false);
self.taxRate = ko.observable(0.06);
self.taxAmount = ko.computed(function() {
return (self.price() * self.taxRate()).toFixed(2);
});
}
//Initialization with data- this could come from anywhere
var items = [
new Item('item1', 10.00),
new Item('item2', 15.00)
];
//Apply the bindings
ko.applyBindings(new ViewModel(items));
HTML
<form>
<table border="1px" align="center">
<tr>
<td>List of Items</td>
<td>Price</td>
<td>Tax</td>
</tr>
<!-- ko foreach: items -->
<tr>
<td>
<input type="checkbox" data-bind="checked: selected" />
<span data-bind="text: name"></span>
</td>
<td>
<input type="text" data-bind="value: price"/>
</td>
<td>
<span data-bind="text: selected() ? taxAmount() : ''"></span>
</td>
</tr>
<!-- /ko -->
<tr>
<td>Subtotals</td>
<td>
<span data-bind="text: priceSubtotal"></span>
</td>
<td>
<span data-bind="text: taxSubtotal"></span>
</td>
</tr>
<tr>
<td>Total Cost:</td>
<td>
<span data-bind="text: totalCost"></span>
</td>
<td>
<input type="button" value="Reset" data-bind="click: reset" />
</td>
</tr>
</table>
</form>
I could really your help! I need to sum a dynamic amount of textboxes but my JavaScript knowledge is way to week to accomplish this. Anyone could help me out? I want the function to print the sum in the p-tag named inptSum.
Here's a function and the html code:
function InputSum() {
...
}
<table id="tbl">
<tbody>
<tr>
<td align="right">
<span>June</span>
</td>
<td>
<input name="month_0" type="text" value="0" id="month_0" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>July</span>
</td>
<td>
<input name="month_1" type="text" value="0" id="month_1" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>August</span>
</td>
<td>
<input name="month_2" type="text" value="0" id="month_2" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>September</span>
</td>
<td>
<input name="month_3" type="text" value="0" id="month_3" onchange="InputSum()" />
</td>
</tr>
</tbody>
</table>
<p id="inputSum"></p>
function InputSum() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf("month_") == 0)
alert(inputs[i].value);
}
}
With a little jQuery, you could do it quite easily, using the attribute starts with selector. We then loop over them, parses their values into integers and sum them up. Something like this:
function InputSum() {
var sum = 0;
$('input[id^="month_"]').each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
}
You could even get rid of the onchange attributes on each input if you modify the code to something like this:
$(function () {
var elms = $('input[id^="month_"]');
elms.change(function() {
var sum = 0;
elms.each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
});
});
function InputSum() {
var month_0=document.getElementById("month_0").value;// get value from textbox
var month_1=document.getElementById("month_1").value;
var month_2=document.getElementById("month_2").value;
var month_3=document.getElementById("month_3").value;
// check number Can be omitted the
alert(month_0+month_1+month_2+month_3);//show result
}