Javascript for each instead of multiple if - javascript

Please, give "direction where to go"
Many input rows. For each row is field class="row_changed"
If value in the field is higher than 0, then ajax pass entire row to php. Each row is included in <tr> </tr> For each <tr> id is set <tr id='row'>
At the moment I can do it only with many if
Need something like: if value in any of field field class="row_changed" is more than 0, then pass corresponding row (inside <tr id='row'>) to php.
Here is some information. Is it suitable for the described case?
<tr id='row1'>
<td>
<input type="text" name="row1[]" id="date_day1" class="row_changed1">
</td>
...
<td>
<input type="text" name="row1[]" id="is_row_changed1" size="1">
<script>
$(".row_changed1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
</td>
<tr>
if ($("#is_row_changed1").val() > 0) {
$.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
$('#load1').html(data1);
$('#is_row_changed1').val(0)
});
var str = $("#row1 :input").serialize();
$("#load1_1").text(str);
}
if ($("#is_row_changed2").val() > 0) {
$.post("_autosave_array.php", $("#row2 :input").serialize(), function (data2) {
$('#load2').html(data2);
$('#is_row_changed2').val(0)
});
var str = $("#row2 :input").serialize();
$("#load2_1").text(str);
}

Something like this should do it:
function doPost(changedRowId,serializeRowId,resultId,serializeResultId){
if ($(changedRowId).val() > 0) {
$.post("_autosave_array.php", $(serializeRowId + ":input").serialize(), function (data2) {
$(resultId).html(data2);
$(changedRowId).val(0)
});
var str = $("#row2 :input").serialize();
$(serializeResultId).text(str);
}
var rowData = [{changedRowId: "#is_row_changed1", serializeRowId: "#row1", resultId: "#load1", serializeResultId: "#load1_1"},
{changedRowId: "#is_row_changed2", serializeRowId: "#row2 ", resultId: "#load2". serializeResultId: "#load2_1"}
];
for(var i = 0; i < rowData.length; ++i){
var data = rowData[i];
doPost(data.changedRowId,data.serializeRowId,data.resultId,data.serializeResultId);
}

I can see that all your input tags have the same name, you can select all of them by name then put your condition/logic inside
sample:
$("input[name='row1[]']").each(function(){
if($(this).val()>0){
$.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
$('#load1').html(data1);
$('#is_row_changed1').val(0)
}
});

Related

Remove first duplicate from an array of objects in JavaScript

On input change I create an array of objects. When any value enter within the input field, it pushes objects into array but the problem is when a text field is updated, it does again push items into array. I need to update the array instead of pushing more items.
var tableData = [];
$('.aantalNumber').change(function(){
var aantalNumberVal = $(this).val()
var Productnummer = $(this).closest('tr').find('.product_number').text();
var Productnaam = $(this).closest('tr').find('.product_name').text();
var verpakking =$(this).closest('tr').find('.verpakking').text();
tableData.push({aantalNumber:aantalNumberVal,Productnummer:Productnummer,Productnaam:Productnaam,verpakking:verpakking });
console.log(tableData);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td><input type="number" class="aantalNumber" name="Aantal1"></td>
<td class="product_number">01454</td>
<td class="product_name">Vendor Handdoeken ZZ vouw</td>
<td class="verpakking">5000 velper verpakking</td>
</tr>
<tr>
<td><input type="number" class="aantalNumber" name="Aantal2"></td>
<td class="product_number">218031</td>
<td class="product_name">Vendor Handdoeken ZZ vouw</td>
<td class="verpakking">5000 velper verpakking</td>
</tr>
<!-- Repeated tr and so on -->
First check if value exist, if available then update else push into tableData
var tableData = [];
$('.aantalNumber').change(function() {
var aantalNumberVal = $(this).val()
var Productnummer = $(this).closest('tr').find('.product_number').text();
var Productnaam = $(this).closest('tr').find('.product_name').text();
var verpakking = $(this).closest('tr').find('.verpakking').text();
if (tableData.some(tableData => tableData.Productnummer === Productnummer)) {
updateTableData(Productnummer, aantalNumberVal);
} else {
tableData.push({
aantalNumber: aantalNumberVal,
Productnummer: Productnummer,
Productnaam: Productnaam,
verpakking: verpakking
});
}
console.log(tableData);
});
function updateTableData(value, aantalNumber) {
for (var i in tableData) {
if (tableData[i].Productnummer == value) {
tableData[i].aantalNumber = aantalNumber;
break; //Stop this loop, we found it!
}
}
}
Working Demo

How to pass a values from two different function to third function in javascript?

I'm trying to code an exercise in html page with javascript, to calculate the mean of a random array of 6 numbers that generated from randomArray() function.
After the first loading of the page and when i click "new problem" button this function recalled to copy the random array in a cell of table.
I write calcMean to calculate the mean of the random array which was passed from randomArray() , and i make the form stop refreshing the page when i hit Enter key when i enter a input , and return the value of input by searchm()
but the problem now is , i want to take the mean ,maxi,mini and inans , to another function to compare the real answer with the user answer and if the condition is yes , something wrote on a div .
the second problem is , i want to take the mean value from calcMean() to show it on the input if i clicked "solution" button which call solution() method, what i must pass to the last function to go write.
<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" id="numbers">
</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>
but in javascript
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 comparing(mean,maxi,mini,inans) {
if(inans==mean){document.getElementById("explain").innerHTML= "correct"+","+inans+"," +maxi+","+mini;
}
}
function solution() {
//some code to take the mean value(realvalue)from calcMean()
//what is parameter should i pass it when i click on solution button to pass it this function
}
Learn Objects https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
with Objects you can return any kind of data types from your functions
for example
function calcMins (nums) {
// ...
return {mean: mean, maxi: maxi, mini: mini}
var values = calcMins(nums)
var mean = values.mean // and so on
at solution() you need to read your document.getElementById("numbers").innerHTML and run
calcNums(nums) from saved numbers. After that you may compare values.mean with your input mean
Not writing full code, cause it's exercise, discover the ways how to use functions, Objects, or Arrays, seems you are familiar with arrays
return [mean, maxi, mini] will work, try it too
You can change to something like this.
As others users said, you can't return multiple values, so convert it to an object
var valuesReturned = null; // initialize variable
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;
valuesReturned = 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":mean, "maxi": maxi, "mini": mini}; //convert to an object
}
function solution() {
if(valuesReturned) {
// make your stuff
// valuesReturned.mean
// valuesReturned.mini
// valuesReturned.maxi
}
}
EDIt
For searchm() function
function searchm() {
if(event.keyCode == 13) {
var values = calcMean();
var inans= values.mini;
return inans;
}
}
Declare a new array in calcMean function and push all mean , mini , maxi
value in new array. And get these value in solution like this :
var myNumArray = randomArray(6,0,99);
var numarr=new Array();
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;
numarr= 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 arr=new Array();
var mean=(parseInt(divide,10));
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
arr.push(mean);
arr.push(maxi);
arr.push(mini);
return arr;
}
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 comparing(mean,maxi,mini,inans) {
if(inans==mean){document.getElementById("explain").innerHTML= "correct"+","+inans+"," +maxi+","+mini;
}
}
function solution() {
alert(numarr[0]); //for mean value
alert(numarr[1]); // for maxi
alert(numarr[2]); // for maxi
}

Remove selected rows on a button click in angular js

I have a table with check box for each row .
I need to remove the rows for the selected check boxes in the table on a button click. (this button is outside ng-repeat).
The index of the selected rows are populated to an array using ng-change function but i'm unable to remove the selected rows on a single button click
Here is the Fiddle
HTML
<div ng-app="approvalApp">
<div ng-controller="SimpleApprovalController" >
<table style="width:90%" border="5" >
<tr>
<th><input type="checkbox" ng-model="CheckAllData" ng- change="selectAll()" /></th>
<th>Date</th>
<th>AssociateID</th>
<th>Check-In</th>
<th>Checkout</th>
</tr>
<tr data-ng-repeat="approval in approvalitems">
<td><input type="checkbox" value="{{approval.ReqId}}" data-ng-model="approval.selected" data-ng-change="SelectDeselect($index)"/></td>
<td>{{approval.Date}}</td>
<td>{{approval.AssociateID}}</td>
<td>{{approval.CheckIn}}</td>
<td>{{approval.Checkout}}</td>
</tr>
</table>
<input type="button" value="Approve" data-ng-model="ApproveIndex" data-ng-click="ApproveRequest()" />
Script
$scope.SelectDeselect=function(index)
{
$scope.getIndexvalues = [];
angular.forEach($scope.approvalitems, function (approval,index) {
if (!!approval.selected) {
$scope.getIndexvalues.push(index);
$scope.CheckAllData = false;
}
});
console.log($scope.getIndexvalues);
};
$scope.ApproveRequest = function () {
$scope.selectedIdsArray = [{}];
angular.forEach($scope.approvalitems, function (item) {
if (!!item.selected) {
$scope.selectedIdsArray.push({ Reqid: item.ReqId, Status: "Approved" });
$scope.CheckAllData = false;
}
});
};
};
So how to use getIndexvalues in approverequest function , or is there any better way to remove it using other angular directive.
I'm a newbie to angular js .
Fiddle: http://jsfiddle.net/jpk547zp/1/
$scope.ApproveRequest = function () {
$scope.selectedIdsArray = [{}];
$scope.approvalitemsNew = [];
angular.forEach($scope.approvalitems, function (item) {
if (!!item.selected) {
$scope.selectedIdsArray.push({ Reqid: item.Date, Status: "Approved" });
$scope.CheckAllData = false;
item.hideThis = true;
console.log($scope.selectedIdsArray);
} else {
$scope.approvalitemsNew.push(item);
}
});
$scope.approvalitems = $scope.approvalitemsNew;
$scope.getIndexvalues = [];
};
Hope this helps.
you can simply do
$scope.ApproveRequest = function () {
$scope.approvalitems = $scope.approvalitems.filter(function(i){
return !i.selected;
});
};

Sum Every Input in Dynamic Table using JQuery

I have created a table where user can add row. And on specific column, there is an input where user can insert a value and jQuery will sum all the value and insert it to another input
So, to make it clear, here's an example:
example
The problem is, after I add more row, it won't sum all the input. It will only sum the FIRST input of the FIRST row but it won't sum when I insert a value in the second, third, forth and ... input.
Here's the table:
<table id="twe">
<thead>
<tr>
<th valign="middle"><center>Amaun</center></th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="amount[]" type="text" class="amount" id="amount[]" value="" /></td>
</tr>
</tbody>
</table>
<button type="button" onclick="addrow('twe')" title="Add">Add</button>
<br/>
<br/>
Sum: <input type="text" id="sum" />
And here's the script
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
$(document).ready(function () {
$('.amount').currencyFormat();
});
$(document).ready(function () {
$(".amount").each(function () {
$(this).keyup(function () {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$(".amount").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#sum").val(sum.toFixed(2));
}
function addrow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
}
}
}
Same goes with the input currency. It only works on the first input of the first row.
Need help
Thank you
The problem lies in when you are binding the events. In your document.ready function you are looping through the .amount items and binding a keyup, but this doesn't account for FUTURE items that will be created. What you want to do is bind all instances AND future instances to run the calculation.
This can be done using the .on event in jQuery. Your document.ready would be updated as follows:
$(document).ready(function () {
$(document).on("keyup", ".amount", calculateSum);
});
Working Fiddle: http://jsfiddle.net/p2Hbm/

trying to get values from a HTML form?

I have a HTML form where i dynamically create elements and set its name , value attributes .
when i tried to access the value say document .formname.nameoftheelement.value then i get the error that value is undefined.
Then i tried to use the following function to access the values .it returns the input elements as 4 but value as null when i it already has predefined value .
function returnTheStoredValues(getTableName) {
//Array arrList = new Array(20);
var tableName = document.getElementById (getTableName);
console.log("The table name" + tableName);
if (tableName) {
var inputs = tableName.getElementsByTagName ('td');
console.log("the inputs are " + inputs.length);
if (inputs) {
console.log("inputs not equal to null")
for (var i = 0; i < inputs.length; ++i) {
console.log("the value in phones table are " + inputs[i].value);
//arrList[i] = inputs[i].value;
}
}
}
//return arrList;
}
The html code is
Phone
<table id="email_table">
<tr>
<td><h3>Email</h3></td>
<td><input value="+" type="submit" onClick="checkTheEmailButtonClicked()"></td>
</tr>
</table>
<table>
<tbody>
<tr>
<td><input type="submit" value ="Save" onclick="getData();"/></td>
<td><input type="submit" value = "Cancel"/></td>
</tr>
</tbody>
</table>
Appreciate all your help .
You seem to want the values of the input elements, so:
function returnTheStoredValues(getTableName) {
var arrList = [];
var table = document.getElementById(getTableName);
var inputs = table.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
arrList[i] = inputs[i].value;
}
return arrList;
}
Because you're getting the TD's and not the INPUT's?
var inputs = tableName.getElementsByTagName('td');
Should be
var inputs = tableName.getElementsByTagName('input');
By the way, if you use a Javascript framework, your code will be happier.
You really need to look into using jQuery for accessing elements through JavaScript.
You could then re-write your function to the following:
function returnTheStoredValues(getTableName) {
return $("#email_table input").map(function() {
return $(this).val();
}).get();
}

Categories