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
Related
Im display some data into table and for each row there is Delete button, when button clicked it should Delete item in array which is stored in localStorage by passing id and than Assign it back to LocalStorage.
HTML:
<table>
<tbody id="ResultProduct">
<tr class="RMAJS">
<td><input type="text" id="item1" name="itemName" value="Computer" /></td>
<td><a data-localstorage-id='ae90ac1a-64c4-49a7-b588-ae6b69a37d47' class="deletebtn">Delete</a></td>
</tr>
<tr class="RMAJS">
<td><input type="text" id="item2" name="itemName" value="Mobile" /></td>
<td><a data-localstorage-id='6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b' class="deletebtn">Delete</a></td>
</tr>
</tbody>
</table>
LocalStorage :
["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"]
0: "ae90ac1a-64c4-49a7-b588-ae6b69a37d47"
1: "6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"
JavaScript :
$('#ResultProduct').on('click', '.deletebtn', function (e) {
var targetElement = $(e.target);
var getID = $(targetElement).attr("data-localstorage-id");
var getLocalStorage = JSON.parse(localStorage.getItem("users"));
for (var i = 0; i < getLocalStorage.length; i++) {
var Val = getLocalStorage[i]
//Here is my problem for example i want to delete this item
//"6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b" from array
//How can i do that ??
localStorage.setItem('users', JSON.stringify(??)); //Assign it back to LocalStorage.
}
$(targetElement).closest("tr.RMAJS").remove();
})
$('#ResultProduct').on('click', '.deletebtn', function (e) {
var targetElement = $(e.target);
var getID = $(targetElement).attr("data-localstorage-id");
var getLocalStorage = JSON.parse(localStorage.getItem('users'));
getLocalStorage = getLocalStorage.filter(e => e !== getID);
localStorage.setItem('users', JSON.stringify(getLocalStorage));
$(targetElement).closest("tr.RMAJS").remove();
});
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
}
I am inserting values in two dimensional array according to my role_id i.e
var tdarray = [[]];
tdarray[40].push(22);
where 40 is my role_id and 22 is its value.
However when i print this value it shows null
alert(tdarray[40][0]); //this shows no value.
I guess two dimensional array in jquery does not allow to insert values at specific position.Can you suggest me what i can do to overcome this.
Entire Code is here
var tdarray = [[]];
var incr = 1;
var check;
$(function () {
$('.toggle_checkbox').change(function () {
if (check === null) {} else {
if (this.name == check) {
incr++;
} else {
incr = 1;
}
}
var tval = $(this).val();
check = this.name;
tdarray[this.name].push(tval);
});
});
Html code
<table border = "0"
cellspacing = "0"
cellpadding = "1" >
<tbody>
<c:forEach items="${accessRightValues}" var="rights" >
<tr style="height: 40px;">
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="1" class="toggle_checkbox"> Add </td>
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="2" class="toggle_checkbox">Update</td>
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="3" class="toggle_checkbox">View </td>
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="4" class="toggle_checkbox">Delete </td>
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="5" class="toggle_checkbox">Assign </td>
</tr>
</c:forEach>
</tbody> < /table>
My problem is that id 40 can hold more than one value .So i want to know how i can do it using multidimensional array in jquery.Also there can be more than one role_id's such as 50,57 which will again hold more than one value.Please help me regarding the same.
I want to pass this two dimensional array in my spring controller.
tdarray[40][0] =1;
tdarray[40][1] =3;
tdarray[40][2] =5;
tdarray[48][0] =2;
tdarray[48][1] =3;
where 40,48 is role_id of a user and 1,3,5 are access_rights which i want to store in database.
In order to use push() function in the key 40 you have to initialize that position as an array as well.
var tdarray = [];
tdarray[40] = [];
tdarray[40].push(22)
// It works now
alert(tdarray[40][0]);
In the code you provided:
var tdarray = [];
...
// Check if it's an array before initialize
if(!tdarray[this.name] instanceof Array) {
tdarray[this.name] = []; // or tdarray[this.name] = new Array();
}
tdarray[this.name].push(tval);
Maybe obvious solution, but if you want to be able to access your values by a key (such as 40), why not use an object?
var tdarray = {};
if ( ! tdarray['40']) tdarray['40'] = [];
tdarray['40'].push(22)
You have to check if its an array already and if its not create it.
var tval = $(this).val();
check=this.name;
if( tdarray[this.name]constructor !== Array){
tdarray[this.name]=[]
}
tdarray[this.name].push(tval);
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)
}
});
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();
}