I create a form with matrix like this:
for(var i = 0; i < rows; i++)
{
for(var j = 0; j < columns; j++)
{
var input = $('<input>')
.attr({
class: 'matrix_cell',
value: 0});
form.appendChild(input[0]);
}
var br = $('<br>')[0];
form.appendChild(br);
}
And I want to read a matrix that user inputted to two-dimensional array and then pass it to php file in ajax query.
I tried this way:
function getMatrix(){
var matrix_row = []
$("#matrix_form").find("input").each(function(i){
var value = $(this).val();
if (!isNaN(value)){
matrix_row[i] = value;
}
});
return matrix_row;
}
But it reads matrix to onedimensional array.
See http://jsfiddle.net/hcbLozd7/
function getMatrix(){
var matrix_row = [];
var ind = 0;
$("#frm").contents().each(function(i,e){ //for all contents in div
if (this.nodeName == "INPUT") //if it's input
{
if (!matrix_row[ind]){ //it matrix doesn't have a new array, push a new array
matrix_row.push([]);
}
matrix_row[ind].push($(this).val()); //add input value to array inside array
}
else{ //when element is br
ind++; //increment counter
}
});
return matrix_row;
}
Related
get all selected checkbox value and display them
wanted to separate each element in the array into new line
$('#generate').on('click', function() {
var array = [];
$("input:checked").each(function() {
array.push($(this).val());
});
$("#selectedSubject").text(array+'<br>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
ok so i fixed it myself
on last line i kept using .text instead of .html thats what made me failed oof
$('#generate').on('click', function() {
var array = [];
$("input:checked").each(function() {
array.push($(this).val());
});
let text = "";
for (let i = 0; i < array.length; i++) {
text += array[i] + "<br>";
}
$("#selectedSubject").html(text);
use each agian to iterate over the new array
ie:
$.each(array, function( index, value ) {
$("#selectedSubject").append( value );
});
I'm having issues to get the stored data in my array. I can't see where is the problem on my function and why is returning undefined elements.
This is the function where I store data in the array:
function getTaskKidData(str) {
var tasks = $('#tasks_data > div');;
var formated_tasks = [];
var formated_kids = [];
formated_homeworks = [];
tasks.each(function(index) {
var task_kids = $(this).find('ul').eq(0).find('li');
var task_homeworks = $(this).find('ul').eq(1).find('li');
if (task_kids.length > 0 && task_homeworks.length > 0) {
task_kids.each(function(index) {
var kid_name = $(this).text().trim();
if (str == "kid"){
var kid = $('#kid_list > li > a[class*="active"]').text().replace(window.location.pathname.split('/')[2],'').trim();
if (kid == kid_name){
formated_kids.push({'name': kid_name});
}
}else{
formated_kids.push({'name': kid_name});
}
});
task_homeworks.each(function(index) {
var homework_name = $(this).find('p').eq(0).text().trim();
var homework_date = $(this).find('p').eq(1).text().trim();
formated_homeworks.push({
'name': homework_name,
'date': homework_date,
});
});
formated_tasks.push({
'kids': task_kids,
'homeworks': task_homeworks,
})
}
});
return formated_tasks;
}
I don't understand why the objects in the output of the array are "li" tags if I'm storing data as text. The output of the array is the next one:
This is the code where I'm trying to get the data:
var tasks = getTaskKidData("kid");
console.log(tasks)
for (let i = 0; i < tasks.length; i++) {
console.log("schedule");
for (let j = 0; j < tasks[i]['kids'].length; j++) {
console.log(tasks[i]['kids'][j]['name']);
}
for (let j = 0; j < tasks[i]['homeworks'].length; j++) {
console.log(tasks[i]['homeworks'][j]['name']);
console.log(tasks[i]['homeworks'][j]['date']);
}
}
And this is the output when I run the code:
Any idea of the problem?
Thanks for reading!!
In your code you have
var task_kids = $(this).find('ul').eq(0).find('li');
and later you log task_kids. The log output shows li elements because that was what you selected.
What I am trying to achieve is to set the placeholder of an input field dynamically. I have an input where I say how many inputs I want to render in the form. On that created inputs I set an onchange event:
function inputOnchange (){
setTimeout(function(){
var createdInputs = document.querySelectorAll("*[class^='createInput']");
createdInputs.forEach( function(item){
item.onchange = function() {
changeFormPlaceholder();
}
})
}, 200);
}
As you see it runs an function when the onchange event is triggered below the function:
function changeFormPlaceholder(){
var inputs = document.querySelector('.formFieldInputs');
var num = 0;
var valueArray = {};
inputs.childNodes.forEach( function(input){
var inputValue = input.value;
var name = 'value' + num++;
valueArray[name] = inputValue;
})
for( var newPlaceholder in valueArray ){
if(valueArray.hasOwnProperty(newPlaceholder)){
console.log("newPLH", newPlaceholder, valueArray[newPlaceholder])
var form = document.querySelectorAll("*[class^='exitIntentInput']");
for(var i = 0; i < form.length; ++i){
// console.log("aaraay", form[i].placeholder);
form[i].placeholder = valueArray[newPlaceholder];
}
}
}
}
Now It changes only on the last input field and sets all input field to the second value.
So how can I change them individually?
Here is an FIDDLE
Type in something in the inputs on the sidebar you will see them appear on the right and now change the input value on the left you see my issue
You run a for loop in the other for loop,
for( var newPlaceholder in valueArray ){
if(valueArray.hasOwnProperty(newPlaceholder)){
console.log("newPLH", newPlaceholder, valueArray[newPlaceholder])
var form = document.querySelectorAll("*[class^='exitIntentInput']");
for(var i = 0; i < form.length; ++i){
// console.log("aaraay", form[i].placeholder);
form[i].placeholder = valueArray[newPlaceholder];
}
}
}
and when the second time of the outer for loop, the new Placeholdee="value1",
for(var i = 0; i < form.length; ++i)
// console.log("aaraay", form[i].placeholder);
form[i].placeholder = valueArray[newPlaceholder];
}
then the inner loop will set placeholder of all indexes of form to valueArray["value1"], the last value of inputs.
The simplest way to solve this problem is that declarie var valueArray as an array but object.
Thus no need to run twice for loops.
Code as follows:
function changeFormPlaceholder(){
var inputs = document.querySelector('.formFieldInputs');
var num = 0;
var valueArray = [];
inputs.childNodes.forEach( function(input){
var inputValue = input.value;
var name = 'value' + num++;
valueArray.push(inputValue);
})
var form = document.querySelectorAll("*[class^='exitIntentInput']");
for(var i = 0; i < form.length; ++i){
// console.log("aaraay", form[i].placeholder);
form[i].placeholder = valueArray[i];
}
}
I'm building a table with HTML and then have created a function which allows me to select a cell. I also have a text field, with a function which will both change the innerText of the cell to the value in the text field and push that value into an array of the data in each table cell. I am then saving it to localStorage.
Here I encounter my error: how can I properly retrieve the data from the localStorage variable and repopulate the table with the values in the array?
Here's my code
omitting the table creation, textEntering, functions because they appear to be working fine
function save() {
localStorage.setItem("tblArrayJson", JSON.stringify(tblArray));
document.getElementById("lblInfo").innerHTML = "Spreadsheet saved.";
}
This is working because in a test function I can print the tblArrayJson in an alert. Next I am trying to load the data back to the table:
function loadSheet() {
var loadedData = JSON.parse(localStorage.getItem("tblArrayJson"));
var loadedTable = document.getElementById("SpreadsheetTable");
var currRow, cell;
alert("the retrieved JSON string contains: " + loadedData);
for (var i = 0; currRow = loadedTable.rows[i]; i++) {
for (var j = 0; cell = currRow.cells[j]; j++) {
cell.innerHTML = loadedData.shift();
}
}
}
The alert displaying the loadedData is working correctly. So what is it about my loop that is failing to insert the array values back into the table? They just stay blank.
Is there a problem with the way I'm using the function? Here is my button with the onclick:
<input id="btnLoad" type="button" onclick="loadSheet();" value="Load" />
localStorage is an object.
A loop through an object for(var key in object) {} is different to a loop through an array for(var i = 0; i < arr.length; i += 1) {}.
If the data looks like
var loadedData = {
0: ["cell1", "cell2", "cell3"],
1: ["cell1", "cell2", "cell3"]
}
the loops should look like
for(var key in loadedData) {
var row = loadedTable.insertRow();
for(var i = 0; i < loadedData[key].length; i += 1) {
var cell = row.insertCell(i);
cell.innerHTML = loadedData[key][i];
}
}
Example
var loadedData = {
0: ["cell1", "cell2", "cell3"],
1: ["cell1", "cell2", "cell3"]
}
function loadSheet() {
//var loadedData = JSON.parse(localStorage.getItem("tblArrayJson"));
var loadedTable = document.getElementById("SpreadsheetTable");
for (var key in loadedData) {
var row = loadedTable.insertRow();
for (var i = 0; i < loadedData[key].length; i += 1) {
var cell = row.insertCell(i);
cell.innerHTML = loadedData[key][i];
}
}
}
loadSheet();
<table id="SpreadsheetTable"></table>
Your for loop is missing the terminating condition. I added that to mine, you're free to modify to fit your needs.
var data = {
0: ["cell1", "cell2", "cell3"],
1: ["cell4", "cell5", "cell6"]
};
// localStorage.tblArrayJson = JSON.stringify(loadedData);
function loadSheet() {
// var data = JSON.parse(localStorage.tblArrayJson);
var table = document.getElementById("SpreadsheetTable");
var row, cell;
// Used Object.keys() to get an array of all keys in localStorage
for (var key of Object.keys(data)) {
row = table.insertRow();
for (var i = 0; i < data[key].length; i++) {
cell = row.insertCell(i);
cell.innerHTML = data[key][i];
}
}
}
loadSheet();
<table id="SpreadsheetTable"></table>
I have a ToDo list, using localStorage... I need to be able to remove the item from the ToDo list... I try to use "dataArray.splice();" But the problem is I don't know how i can remove the object when the position is unknown...
function getTodoItems() {
for (var i = 0; i < dataArray.length; i++) {
if (!dataArray[i].listItem.length) return;
var itemList = document.getElementById("my-todo-list");
var list = document.createElement("li");
itemList.appendChild(list);
list.innerHTML = dataArray[i].listItem;
var spanItem = document.createElement('span');
spanItem.style.float = 'right';
var myCloseSymbol = document.createTextNode('\u00D7');
spanItem.classList.add("closeBtn");
spanItem.appendChild(myCloseSymbol);
listItems[i].appendChild(spanItem);
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
console.log(dataArray);
}
var list = document.getElementsByTagName('li');
list[i].onclick = function() {
this.classList.toggle("checked");
}
}
}
Then probably get its position:
const position = dataArray.indexOf(/*whatever*/);
dataArray.splice(position, 1);
You can get the position of the element using 'indexOf'
let pos = dataArray.indexOf(element);
dataArray.splice(pos,1)
IndexOf() wont work if you are trying to find the index of an entire object or array inside the array.
If you need to find the index of an entire object inside your array, you test each one's value to find out if it is the correct one. I would use findIndex();
Try this in your console:
var array = [];
for (var i = 0; i < 10; i++ ){ array.push({item: i}) }
console.log('Current Array: ', array);
var indexOfResult = array.indexOf({item: 3});
console.log('indexOf result: ',indexOfResult);
var findIndexResult = array.findIndex(object => object.item === 3);
console.log('findIndex result: ',findIndexResult)