Array from php to html input to JS - javascript

Here's what i'm trying to accomplish. Insert an array from php into an HTML form and then have that array be pushed in a JS array.
PHP
$proxiearray = array();
if($row7['attribute_0'] != NULL) { array_push($proxiearray,$row7['attribute_0']);}
if($row7['attribute_1'] != NULL) { array_push($proxiearray,$row7['attribute_1']);}
<input type="hidden" class="proxie_attributes" value="'.htmlspecialchars(json_encode($proxiearray)).'">
Now what i want with that is on uppon a certain task on the client side for my JS to take that aray and push it in another one.
JS
attributesArray[counter] = new Array();
if(proxiearray) { attributesArray[counter] = proxiearray; }
If i alert the array i get
["1","4"],5,6
This just pushed in the array the ["1","4"] but what i would want it to push is have a result like
1,4,5,6
I know i could go with X amount of inputs although that is not a solution since i may have to use a bigger ammount of attributes in the future.
EDIT: The alert is on the attributesArray.
The attributesArray[counter] alert is ["1","4"]

You can use following;
if ($(this).find('div .proxie_attributes').length > 0) {
var proxiearray = JSON.parse($(".proxie_attributes").val());
attributesArray[counter] = new Array();
if(proxiearray) {
attributesArray[counter] = proxiearray;
}
}

Related

Creating array with multiple objects Javascript from XML data

I have a problem approaching this problem and I'm unsure in how to solve it. My XML looks like this:
<Order>
<OrderLines>
<ProductLine>
<ManufacturerArticleNo>ARTICLENUMBER</ManufacturerArticleNo>
<Serials>
<SerialNumber>
.
.
<SerialNumber>
</Serials>
<ProductLine>
<ManufacturerArticleNo>ARTICLENUMBER</ManufacturerArticleNo>
<Serials>
<SerialNumber>
.
.
<SerialNumber>
</Serials>
What I want to do is create an array, and fill it with objects with articleNumber, serialnumbers. Where I'm stuck is getting all the serialNumbers from a node to the corresponding article number.
Edits after comments:
Expected output: An array filled with the objects with ArticleNumber, Corresponding serial number. One serial number = one object.
Current Code:
//Create Article List
var artList = [];
//Get articles
var nodeArticleNo = xmlDoc.getFirstNode('//ProductLine/ManufacturerArticleNo');
while(nodeArticleNo != null) {
var artNo = xmlDoc.getNodeText('//ProductLine/ManufacturerArticleNo');
//Get Serials
var nodeSerialNumber = xmlDoc.getFirstNode('//Serials/SerialNumber');
while(nodeSerialNumber != null){
var serialNo = xmlDoc.getNodeText('//Serials/SerialNumber');
artList.push({ArticleNumber: artNo, SerialNumber, serialNo});
nodeSerialNumber = xmlDoc.getNextNode(nodeSerialNumber);
}
nodeArticleNo = xmlDoc.getNextNode(nodeArticleNo);
}
This is how I have been trying to solve it but I hate the while in a while and it is not working as intended
Thank you!

Set PHP form array variable with javascript

I'm currently in the process of passing a javascript array though to a form for submission with a file upload.
As it currently stands i have been able to pass the javascript array though to the form but not quite how i would like.
The initial javascript values i have stored in the array are as follows:
Folder 1/File 1.txt
Folder 1/Folder 2/File 2.txt
Once passed though the array output from the PHP variable is as follows:
Array ( [0] => Folder 1/File 1.txt,Folder 1/Folder 2/File 2.txt )
What i would like to do however if possible is alter the array to the following:
Array ( [0] => Folder 1/File 1.txt,
[1] => Folder 1/Folder 2/File 2.txt )
The HTML code the array is being passed to from javascript:
<input type="hidden" id="pathArray" name="pathArray[]" value="pathArray">
The current javascript code:
let picker = document.getElementById('picker');
var pathStructure = [];
var i = 0;
picker.addEventListener('change', e =>
{
for (let file of Array.from(e.target.files))
{
pathStructure[i] = file.webkitRelativePath;
i++;
};
document.getElementById('pathArray').value = pathStructure.toString();
});
The main issue i'm having and at the moment is setting the array position values of the form for submission. I'm able to input the array into the form but not able to set the individual array positions and as of yet have been unable to find the relevant documentation on how to achieve this somehow like the following:
let picker = document.getElementById('picker');
var pathStructure = [];
var i = 0;
picker.addEventListener('change', e =>
{
for (let file of Array.from(e.target.files))
{
pathStructure[i] = file.webkitRelativePath;
document.getElementById('pathArray').value[i] = pathStructure[i].toString();
i++;
};
});
Any help would be greatly appreciated and if at all there is any further detail that would be required please let me know and i'll do my best to expand or provide any additional information!
toString method joins the array and returns one string containing each array element separated by commas. So you lose the array information.
I usually did something like this with adding multiple inputs:
<form id="form">
<input type="hidden" class="pathArray" name="pathArray[]">
<input type="hidden" class="pathArray" name="pathArray[]">
...
</form>
The idea is that for each value you create a new input. You will have input for Folder 1/File 1.txt, another input for Folder 2/File 2.txt and so on. The final code could look something like this
let picker = document.getElementById('picker');
var pathStructure = [];
var i = 0;
picker.addEventListener('change', e =>
{
for (let file of Array.from(e.target.files))
{
pathStructure[i] = file.webkitRelativePath;
var input = document.createElement("input");
input.type = 'hidden';
input.name = 'pathArray[]';
input.classList.add('pathArray');
document.getElementById("form").appendChild(input);
document.getElementsByClassName('pathArray')[i].value = pathStructure[i].toString();
i++;
};
});
Hope you get the idea.

Populating a Select Box with Data from Google Sheet

I have a Google site and am currently using the following script to populate my select box with data from the google sheet that is serving as my database:
<? var stringified = getData(); ?>
<?var data = JSON.parse(stringified)?>
<select size="10" id="userChoice">
<? for (var i = 0; i < data.length; i++) { ?>
<option>
<?= data[i] ?>
<? } ?>
</select>
This loads the page with the select box populated with every entry in the database. I'm wondering if this is the best way to go about it. What I would really like to do is have the contents of the select box be a little more dynamic.
I wrote out a script to filter through (by date) the contents of the Google Sheet, but I can't quite figure out how to have those filtered results show up in the above select box. I've tried several possible solutions, but keep hitting road blocks with them. Below is the function on the client side that passes the dates to the server side (note that I realize nothing in the below scripts would pass the data back to the select box. This is just to show how I am filtering through the data):
//Takes the dates that were entered into the first two date pickers and sends them over to the server side stringified. The server side then uses these dates to filter out jobs not within the given time period.
function dateFilter(){
var date = {};
//dates pusehd into array
date[0] = document.getElementById("startDate").value;
date[1] = document.getElementById("endDate").value;
//array stringified
var dates = JSON.stringify(date);//Convert object to string
google.script.run
.getData2(dates);
Then here is the code that filters through the database on the server side:
function getData2(dates) {
var ss = SpreadsheetApp.openById('1emoXWjdvVmudPVb-ZvFbvnP-np_hPExvQdY-2tOcgi4').getSheetByName("Sheet1");
var date = JSON.parse(dates);
var dateArray = [];
for (var k in date) {//Loop through every property in the object
var thisValue = date[k];//
dateArray.push(thisValue);
};
var startDate = Date.parse(dateArray[0]);
var endDate = Date.parse(dateArray[1]);
var jobReference = [];
var job;
var dateCell1;
var dateCell;
if ((startDate==NaN) || (endDate==NaN)){
for (var i = 2; job!=""; i++){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
};
}
else{
for (var i = 2; job!=""; i++){
dateCell1 = ss.getRange(i,3).getValue();
dateCell = Date.parse(dateCell1);
if (startDate<=dateCell&&endDate>=dateCell){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
Logger.log("here it is"+jobReference);
}
else{
}
}
};
var jR = JSON.stringify(jobReference);
return jR;
}
Now I've tried several things, having a success handler change the line <? var stringified = getData();?> to use getData2 doesn't seem to work (it yells at me that variable I'm trying to parse is undefined on the server side). So I tried putting an if/else in that would only have it parse if the variable was != to undefined, that didn't work either. Any suggestions would be appreciated.
I figured it out! This is functional, but perhaps not best practices, so if someone has any input, feel free to chime in.
So the first bit of code on the client side for the select box I left the same.
The next bit, where I send the dates over to the server side was changed to this:
function dateFilter(){
var sdate = document.getElementById("startDate").value;
var edate = document.getElementById("endDate").value;
google.script.run.withSuccessHandler(dateSuccess)
.getData2(sdate,edate);
}
So, since it was only two variables I took out the part that pushed it to an array. This eliminated the problem of parsing on the server side and thus having an undefined variable. I also added a success handler.
The server side code was left essentially the same, however I did change the for loop slightly. Instead of having it loop through the database until it found a blank cell in a particular column, I added var last = ss.getLastRow(); and had it loop though until i<= last. This kept the code from timing out on me.
Next I added the function I used for the success handler:
function dateSuccess(jobs){
document.getElementById('userChoice').options.length = 0;
var data = JSON.parse(jobs)
for (var i = 0; i < data.length; i++) {
var option = document.createElement("option");
option.text = data[i]
var select = document.getElementById("userChoice");
select.appendChild(option);
}
}
Works like a charm!
Scriptlets i.e. <? ?> are compiled and run when the page is created using execute function. They are not for dynamic modification of the web page. To modify the options based on a server returned data, in this case from getData(). You would do something like this
Firstly you set your google.script to call modifyoptions function on success
google.script.run.withSuccessHandler(modifyOptions)
.getData2(dates);
The above will code will automatically pass the return value of getData2 i.e Jr value to modifyOptions function
function modifyOptions(jobReference){
var selOpt = document.getElementById("userChoice")
selOpt.innerHTML ="" // Remove previous options
var options = ""
var data = JSON.parse(jobReference)
for (var i = 0; i < data.length; i++) {
options += "<option>"+data[i] +</option> //New string of options based on returned data
}
selOpt.innerHTML = options //Set new options
}
You can find a working example of how to modify the select-options in javascript here
Hope that helps!

Validating multiple fields in an HTML form using JS

I have a signup form which is having some 12 fields. I want to validate data in those fields. First step is to check if any field is empty. One way of doing this is to get each field using Jquery and check if it is empty. I was planning to create a var array and check status of each field inside a loop using this code :
var input = new Array();
input[0] = $('.fullName')[0];
input[1] = $('.emailID')[1];
input[2] = $('.phno')[2];
input[3] = $('.userName')[3];
input[4] = $('.password')[4];
input[5] = $('.batch')[5];
input[6] = $('.nickname')[6]
input[7] = $('.enrno')[7];
input[8] = $('.dob')[8];
input[9] = $('.fromCity')[9];
input[10] = $('.currcity')[10];
input[11] = $('.interests')[11];
input[12] = $('.currComp')[12];
input[13] = $('.currDesig')[13];
Now I have to run a loop to get the values and check if any field is blank.
I am writing this code for checking
for(i=0;i<14;i++)
if(input[i].val()=="")
{
// do my work
}
But the problem is that the last 15 lines of code are pointing to actual HTML DOM element, so I can't use input[i].val() directly to access the value. Any way out?
You seriously need to just add a common class to the elements that needs validation, and then do
var is_valid = $('.validate_these').filter(function() {
return $.trim(this.value) === "";
}).length === 0;
That gets all the elements with that class, and filters them based on wether or not the value is empty. If no empty elements where found, it's valid

minimized code for arrays in js

I have three arrays in js and now i want to add empty check on them..so please help me in short/ minimized code for the empty array check.My js code is
var selectedfirst = jQuery('select#frsts').val();
var selectedsecond = jQuery('select#secnds').val();
var selectedthird = jQuery('select#thirds').val();
var lastfindal = selectedfirst.concat(selectedsecond); // Array concatination
var getfinal = lastfindal.concat(selectedthird); // Array concatination
I know how can i process empty check on single array but due to contcatenation the code goes longer . i contcate first array to second then concate to third.I want to concate array when they are not empty. like selectedfirst.length > 0.if anyone not understand fully i will provide more detail on request.Thanks in advance
After working i fix the issue.I created new array like
var hege = [];
if (selectedfirst!== null) {
alert('not emtpy');
var hege = hege.concat(selectedfirst);
}
the same condition for other too.

Categories

Resources