I've looked all over online for something that could aid me to fill an empty array with given values the user inputs from a text box that will get stored inside an array.
So far I have the following code:
var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "<br />" + "<br />";
var x = [];
x.push(text);
console.log(x);
When I input something in the textbox and see what happens in the console it tends to replace the previous value that was sent there first.
For example, if I wrote "Hello", this will get sent into the array so it'll be seen as:
["Hello"]
But if I type in something again, hoping that the result will continue to store the data being inputted inside, it does this:
*Writes down "Hi" in the text box:
["Hi"]
I want the result to be something like this:
["Hello", "Hi"]
I am aware my code does need tweaking and I am doing something wrong which is causing that result, but I can't seem to figure it out.
I'm looking for an answer in vanilla JavaScript.
Thank you.
The problem is you are redeclaring variable x and initializing it with an empty array, every time when you run that code. Make the x a global variable by moving it out of the current function or block
var x = [];
Another Block
var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "<br />" + "<br />";
x.push(text);
console.log(x);
var x = [];
function() {
var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "<br />" + "<br />";
x.push(text);
console.log(x);
}
something like this should fix your problem. You were declaring x as an empty array every time you ran your javascript which would reset it to an empty arry.
I am trying to do nested queries in order to insert into a table based apon an earlier select statement. However I am running into trouble because my first select statement selects and AVG() of a row. I have not been able to find a way to get the result row object that I have to select the property 'AVG(row)' instead of the trying to call .AVG() on something. The code is below and any help would be appreciated.
var sql1 = 'SELECT tropename, AVG(criticScore) FROM tropesWithScore where tropeName = '+ '\'' + trope + '\'';
//console.log(sql1)
con.query(sql1, function (err1, result1) {
if (err1) throw err1;
Object.keys(result1).forEach(function(key) {
var row2 = result1[key];
var trope2 = row.tropeName;
console.log(trope2)
var avgScore = row.AVG(criticScore)
console.log(avgScore)
sql = 'INSERT INTO TropesWithAverageScores (tropeName, criticScore) VALUES (' + trope2 + ',' + '\'' + avgScore + ')';
///console.log(sql)
con.query(sql, function (err, result) {
if (err) {}
});
});
});
Fixed it myself,
first, I was getting the attribute on row, not row2 object.
Secondly I simplified it by aliasing my first select state, so it now reads
SELECT tropename, AVG(criticScore) as avgCS FROM tropesWithScore where tropeName = '+ '\'' + trope + '\'';
Hope this helps someone else!
I have a function that I need to use for filtering table rows:
setFilterString("Filter");
But I have a problem. I can set it to
setFilterString("OrderID = 5");
and it will filter out row where OrderID is equal to 5 but if i try using a variable that has a value taken before like this
setFilterString("OrderID = vOrderID");
I get error "Invalid column name 'vOrderID'." (as vOrderID is variable and not a column, I guess)
I have seen somewhere in filter section inputting something like this ("OrderID = '" & vOrderID & "'") but it doesn't have any result at all for me. Doesn't even throw any error in the console.
JavaScript assumes you are just passing a string to the function. If you want to use the variable, you should try this:
setFilterString("OrderID = '" + vOrderID + "'"); // Results in OrderID = '5'
or
setFilterString("OrderID = " + vOrderID); // Results in OrderID = 5
depending on the body of your function.
Use + instead of &: setFilterString("OrderID = " + vOrderID) should work.
Use "+" for merge strings:
setFilterString("OrderID = " + vOrderID)
You can also try to use ${idvOrderID} inside string:
setFilterString("OrderID = ${vOrderID}")
Or:
setFilterString(sprintf("OrderID = %s", vOrderID))
Remember about difference between ' and "
I am saving table data to a json object. The table data is coming from txt inputs and textareas in the table cells.
I'm running into a problem with CR/LF characters in the JSON elements holding the textarea data. The JSON data gets saved to the database fine, but when I pass it back to the jQuery function that populates the table using that data, I get this:
SyntaxError: JSON.parse: bad control character in string literal at line 1 column 67 of the JSON data
var array = JSON.parse(notes),
in the console.
I put the JSON data in Notepad++ with Show All Characters on and the CR/LF was at column 67.
Here's a sample of JSON data that I'm working with:
[["","","",""],["","9/23/14","",""],["","30789 detail, x_vendor_no**CR/LF HERE**
20597 header","",""],["","99 del invalid x_vendor_no","",""],["","30780","",""],["","","",""],["","","",""],["","","",""]]
Is there a way to allow CR/LF in the data?
UPDATE
11684's suggestion to use replace to remove the \r part of the CRLF won't work. Here's why:
Here's the complete function that uses the JSON data:
(Updated to work with Update #2 code below)
function PopulateTaskTableWithNotes(tableID,notesArray) {
// JSON parse removed per answer suggestion
var r, c, note;
for (r = 0; r < notesArray.length; ++r) {
for (c = 0; c < notesArray[r].length; ++c) {
note = notesArray[r][c];
$('#' + tableID + ' tr:nth-child(' + (r + 1) + ') td:nth-child(' + (c + 1) + ')').children(':first-child').val(note);
}
}
}
I still get the error on the line that tries to parse the JSON data. The replace function apparently can't "find" characters within an array element.
UPDATE #2
Here's how I am creating the array:
var siteID = $('#ddlUserSites option:selected').val(),
numRows = $('#' + tableID + ' tr').length,
numCols = $('#' + tableID).find('tr:first th').length,
notesArray = new Array(numRows),
rowNum = 1,
note = '',
colNum;
while (rowNum <= numRows) {
notesArray[rowNum] = new Array(numCols);
// Reset colNum for next row iteration
colNum = 1;
while (colNum <= numCols) {
note = '';
if ($('#' + tableID + ' tr:nth-child(' + rowNum + ') td:nth-child(' + colNum + ')').children(':first-child').is('input,textarea')) {
note = $('#' + tableID + ' tr:nth-child(' + rowNum + ') td:nth-child(' + colNum + ')').children(':first-child').val();
}
notesArray[rowNum][colNum] = note;
//console.log('Note for rowNum ' + rowNum + ', colNum ' + colNum + ': ' + note);
colNum++;
}
// Remove first element in current row array
notesArray[rowNum].shift();
rowNum++;
}
// Remove first element in array
notesArray.shift();
JSON.stringify(notesArray); // Added per an answer here
console.log('Final notesArray: ' + $.toJSON(notesArray));
$.ajax({
data: {saveTaskNotes: 'true', userID:userID, siteID:siteID, taskTable:tableID, notes:notesArray},
success: function(data) {
console.log('Save task notes data: ' + data);
}
});
The "Final notesArray" console output looks fine, but now, with stringify added, the function above (PopulateTaskTableWithNotes) console output shows that it's reading through every character in the array as a separate element!
Maybe this will help too, as far as what's happening to the data between the creating and reading functions: the array is being saved to a single MySQL database field and then retrieved for the PopulateTable function via $.ajax() (on both ends).
Having said that, do I need to look at what I'm doing with/to the array in the PHP code?
UPDATE #3
Here's the PHP function that takes the data in and writes to the MySQL db:
function SaveTaskNotes($userID,$siteID,$taskTable,$notes) {
$notes = json_encode($notes);
$insertUpdateTaskNotesResult = '';
$insertTaskNotes = "INSERT INTO userProgress (userProgressUserID,userProgressSiteID,userProgressNotesTable,userProgressNotes) values ($userID,$siteID,'" . $taskTable . "','" . $notes . "')";
$log->lwrite('$insertTaskNotes: ' . $insertTaskNotes);
$resultInsertTaskNotes = #mysqli_query($dbc,$insertTaskNotes);
if ($resultInsertTaskNotes) {
$insertUpdateTaskNotesResult = 'insertTaskNotesSuccess';
} else {
if (mysqli_error($dbc) != '') {
$log->lwrite('INSERT TASK NOTES: An error occurred while attempting to add the task notes. Query: ' . $insertTaskNotes . ', mysqli_error: ' . mysqli_error($dbc));
}
$insertUpdateTaskNotesResult = 'insertTaskNotesFail';
}
echo $insertUpdateTaskNotesResult;
}
And here's the function that gets the data from the db and sends it to the above $.ajax function:
function GetUserTaskNotes($userID,$siteID,$taskTableID) {
$queryGetUserTaskNotes = "SELECT userProgressNotes FROM userProgress WHERE userProgressUserID = $userID AND userProgressSiteID = $siteID AND userProgressNotesTable = '" . $taskTableID . "'";
$log->lwrite('$queryGetUserTaskNotes: ' . $queryGetUserTaskNotes);
$resultGetUserTaskNotes = #mysqli_query($dbc,$queryGetUserTaskNotes);
if ($resultGetUserTaskNotes) {
$taskNotes = mysqli_fetch_assoc($resultGetUserTaskNotes);
$log->lwrite('Retrieved $taskNotes[\'userProgressNotes\']: ' . $taskNotes['userProgressNotes']);
echo $taskNotes['userProgressNotes'];
} else {
if (mysqli_error($dbc) != '') {
$log->lwrite('GET TASK NOTES: An error occurred while attempting to retrieve the task notes. Query: ' . $queryGetUserTaskNotes . ', mysqli_error: ' . mysqli_error($dbc));
}
echo 'getTaskNotesFail';
}
}
In both the save and get functions the $log output shows that the array never changes (with the above js/php code) and pasting the array in to notepad++ shows that the CR/LF is still there throughout.
Don't use JSON.parse, the data is already JSON and Javascript can work with it.
You only need it when passing a string, imagine JSON.parse() beeing like string2json().
I think this might already be a solution to your problem, I've never had issues with new line characters.
As Luis said, the problem is not your client (Javascript, jQuery), besides the JSON.parse, but the providing site is wrong.
Example for PHP:
<?php
echo json_encode(array("test" => "
x"));
PHP properly escapes the characters:
{"test":"\r\n\r\n\r\nx"}
But the source of your data is providing malformed JSON.
To fix the JSON issue, either use prepared statements or use:
$notes = str_replace('\', '\\', json_encode($notes)); // in SaveTaskNotes
Well, the error is on the input data (showed in question). You can't have an CR or LF inside a literal in a JSON string. What you can have are that chars escaped as \r \n. The problem is on other side, where escaped codes are replaced by actual chars and therefore the full JSON string becomes invalid.
I have a small piece of code that generates an array with values based on a triangle. I will post the array below.
var endwallPanelLengths = [totalHeightInches];
var i = 0;
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
document.getElementById("test83").value="4 - " + endwallPanelLengths[i];
i++;
}
This array will have anywhere between 2 to 100 indexes. I want the code to write all of the values separated by breaks into a <textarea> with the id="test83".
If I run the code as it is set up above it will only write the value in array [1] not [0] or any of the others. How can I get it to write all of them so that they come out looking like this...
4 - 140 this is the value of array position [0]
4 - 126
4 - 116 and so on?
You keep replacing the value
document.getElementById("test83").value="4 - " + endwallPanelLengths[i];
You would need to append to the value
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
better yet, build up the values and set the value once
var endwallPanelLengths = [totalHeightInches],
i = 0,
output = [];
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
output.push("4 - " + endwallPanelLengths[i]);
i++;
}
document.getElementById("test83").value = output.join("\n");
If I'm understanding you correctly, that you want the array displayed with one item per line in your textarea, then you should be able to ditch your loop completely, and just do it in one shot.
document.getElementById("test83").value = endwallPanelLengths.join('\n');
Although it also looks like you're prepending '4 -' to each value. If that's the case, then you could just add one extra step to get those fours added:
var arr = endwallPanelLengths.map(function(item){ return '4 - ' + item; });
document.getElementById("test83").value = arr.join('\n');
Just be sure to grab the shim for Array.prototype.map from here if you need to support IE8
HTML:
<div id="holder"></div>
JavaScript:
var endwallPanelLengths = [totalHeightInches];
var i = 0;
var holder = document.getElementById("holder");
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
var e = document.createElement('div');
e.innerHTML = "4 - " + endwallPanelLengths[i] + "<br />";
holder.appendChild(e.firstChild);
i++;
}
Hopefully that does for you what you want. In your example, in your loop, you're setting the newest value to the same element, thus overwriting any previous values.