How to edit a one dimentional array via input form - javascript

I have written an array to capture a SharePoint input field and add the entry time with JavaScript and then set a history field to the value of the array. This works fine. However, I would now like to be able to edit (and delete) the entries in this array via an edit form, but cannot seem to understand how the pick out the specific entry.
I have tried using splice but that doesn't seem to work. I was able to get the delete to work, but it just deleted the last object in the array, not the specific one that I wanted to delete. I have reviewed w3schools on this topic but I guess it is not sinking in. I will have no idea what the user enters, so its not like I can hard code something like the examples on that site.
//this is adds a button under the statusupdate field. The button will add the status updates to the status history field.
function loadhistory() {
historyform = "<table id=\'TTTT\' style=\'padding:1px;border- collapse:collapse;width:800px;vertical-align:text-top;border:2px\'>"
historyform += "<tr><td colspan=3><div><button type=\'button\' id=\'add2\' style=\'font-weight:bold;\' onclick=\'statusupdatehistory ();\'>Add History</button></div></td></tr></TABLE>";
jQuery("#historyforms").html(historyform);
} //End Load Form
loadhistory();
// builds the array to store the status updates in.
var myArray = new Array();
function statusupdatehistory() {
var entryTime2
entryTime2 = moment.tz('America/New_York').format('M/D/YY h:mm A z');
var etime = entryTime2
//this is the update number. It is manually entered when sending the full form communication. Maybe this can be set to i++ then
// update the ffcUpdate field. This would prevent the miscounting of the update forms. It could i++ when the status update is added
//var updatenumber= getFieldValue("ffcUpdate");
// && statusupdate.trim()!=''
var statusupdate = getFieldValue("ffcStatusUpdate");
if (!(typeof statusupdate === 'undefined') || statusupdate!=null || statusupdate ==='') {
// myArray.push("<tr><td>"+ entryTime2 +"</td>"+" "+"<td>"+ statusupdate + "</td></tr>");
myArray.unshift(etime +"<td>"+ statusupdate);
}
setFieldValue("ffcStatusHistory", myArray.join("|"));
buildhistorytable ();
} // end function
function loadHistoryrecord () {
// alert("Whoops,this feature is not ready just yet!")
};
function delHistoryrecord () {
alert("Whoops,this feature is not ready just yet!")
// myArray.splice(1, 1);
// setFieldValue("ffcStatusHistory", myArray.join("|"));
// buildhistorytable ();
};
// console.log(myArray);
// //document.getElementById('dffs_ffcStatusUpdate').value = '';
function buildhistorytable () {
myArray = getFieldValue("ffcStatusHistory", true).split("|");
historytable = "<table cellspacing=\"0\" cellpadding=\"0\" sytle=\'width:692px;padding-left:10px;padding-right:10px;margin:10px;\'>";
historytable += " <tbody>"
historytable += " <tr>"
historytable += " <table class=\"tbl_border_blk_3b\" style=\"width:700px;font-weight:normal;font-family:Calibri;color:black;font- size:11pt\" align=\'left\'>"
historytable += " <th bgcolor=\"#6699CC\"colspan=4 style=\"width:692px;font-weight:normal;font-family:Calibri;color:black;font- size:11pt;text-align:center;\" >Update History</th>"
//historytable += " <tr style=\'font- weight:bold;color:white; background-color:#123456;text-align:center; padding:10px;\'><td width=\'25%\'>Entered Time</td><td>Status Update</td><td width=\'15%\'>Edit</td><td width=\'17%\'>Delete</td></tr>";
historytable += " <tr style=\'font- weight:bold;color:white; background-color:#123456;text-align:center; padding:10px;\'><td width=\'25%\'>Entered Time</td><td>Status Update</td></tr>";
historytable += " <tbody>"
if (myArray == null || myArray == undefined) {
historytable += "<tr><td colspan=4>There are no Status updates</td></tr>";
} else {
for (var i = 0, len = myArray.length; i < len; i++) {
historytable += "<tr id=\'row" + i + "\'>";
historytable += "<td>" + myArray[i] + "</td>";
//Edit
historytable += "<td width=10%><div style=\'text- align:center\'><a href=\'javascript:loadHistoryrecord(" + i + ")\'><i class='fas fa-edit' style='font-size:27px;color:green'></i></a></div></td>";
//Delete
historytable += "<td width=10%><div style=\'text- align:center\'><a href=\'javascript:delHistoryrecord(" + i + ")\'><i class='fas fa-trash-alt' style='font- size:27px;color:red'></i></a></div></td>";
historytable += "</tr>"
} //End For
} //End if
//historytable += " <br>"
historytable += " </tbody>"
historytable += " </table>"
historytable += " </tbody>"
historytable += "</table>";
jQuery("#historytables").html(historytable);
};
buildhistorytable ();
So if I had 5 entries in my status update field, and I wanted to modify the 3rd entry, how would I pluck just that entry out of the array to edit it?

Quoting from question:
However, I would now like to be able to edit (and delete) the entries
in this array via an edit form, but cannot seem to understand how the
pick out the specific entry.
I am bit confused to work on your code(sorry), instead providing a sample code performing what you asked for:
I have tried using splice but that doesn't seem to work
Lets use splice and indexOf to remove an item:
var arr=[3,5,7,9,11,13];
//lets remove 5:
var index=arr.indexOf(5);
if(index!==-1)
{
arr.splice(index,1); //you want to remove only one element
}
console.log(arr);
This will remove 5 from your array.
To pluck and edit an item:
lets edit value of 9.
var index=arr.indexOf(9);
if(index!==-1)
{
arr[index]=99; //your value
}
console.log(arr);
Just copy paste the code in browser console to see output.
P.S: I just focused how to edit and delete an specific element as your mentioned, that's why I didn't work with your code. Hope this helps.

Related

textarea clears when using innerhtml [duplicate]

I have a problem concerning multiple file uploads in javascript. I am trying to create my own multiple file upload by dynamically adding inputs. This is all easy as pie, but the problem is that whenever I add a new , my previous input-fields of the type "file" get reset.
If I remove the last lines of code where I alter the innerHTML of my parent div, the values of my do not get reset. Does anyone know how this problem can be solved? The javascript code can be found below. Thanks in advance.
if(document.getElementById("upload_queue").innerHTML.indexOf(_item) == -1)
{
var _row = "<tr id='queue_row_" + items_in_queue + "'>";
_row += "<td>";
_row += "<div class='remove_uploaded_image' onclick='remove_from_queue(" + items_in_queue + ")'></div>";
_row += "</td>";
_row += "<td>";
_row += _item;
_row += "</td>";
_row += "</tr>";
document.getElementById("upload_queue").innerHTML += _row;
document.getElementById("upload_image_" + items_in_queue).style.display = "none";
items_in_queue++;
document.getElementById("uploader_holder").innerHTML +=
'<input id="upload_image_' + items_in_queue +
'" name="upload_image_' + items_in_queue + '" accept="image/jpeg" type="file"' +
'onchange="add_to_upload_queue()" style="display: inline;" />';
}
Yeah... you're going to want to use appendChild instead of modifying the inner HTML:
var myInput = document.createElement("INPUT");
// do stuff to my input
var myContainer = document.getElementById("uploader_holder");
myContainer.appendChild(myInput);
That's the general gist of what you have to do - let me know if you need somethign more specific, but it looks like you've got a good hold on JS already... You're going to want to do that in almost all cases rather than setting inner HTML... So, building your TR as well... you'll have to append the TD to the TR, you'll have to append the TD with your input, you'll have to append your targeted table with the TR, etc.

Jquery is not completing the append of elements - last two are not appeneded

I receive an array from ajax call and build a series of radio boxes using the array's elements. Only some of the radio boxes are appended, not all, eg. out of 4 elements in the array only first two are appended, out of 3 elements only the first is appended.
The array from ajax call is as expected. The for loop works correctly, ie. the text to be inserted is built as expected, yet the append is not appending the expected lot but only some. I've run out of ideas...
here's my html:
<table class="std-table">
<tr>
<td><div id="areas"></div></td>
</tr>
</table>
and javascript:
$(document).on('pagebeforeshow', '#property-details-page', function(){
all_areas = new Array();
var Q001Data = "sql=Q001&dbcall=sql_get_results_array&memid="+<?php echo $member_id?>+"&propid="+<?php echo $property_id?>;
$.ajax({ // ### AJAX to get ALL AREAS on page load ###
url:"pl_process_ajax_call_property_features.php",
type:"POST",
data : Q001Data,
success:function(msg){
$("#areas").html('<fieldset id="all-areas-radio" data-role="controlgroup" data-mini="true"></fieldset>');
all_areas = JSON.parse(msg);
var textToInsert = '';
var i;
for (i = 0; i < all_areas.length; ++i) {
var area = JSON.stringify(all_areas[i][0]);
alert(area+i);
textToInsert += '<input type="radio" class="all-areas" name="property-area" id="' + area + '" value="' + area + '"><label for="' + area + '">' + area + '</label>';
alert(textToInsert);
}
$("#all-areas-radio").append(textToInsert);
$("[type=radio]").checkboxradio();
$("[data-role=controlgroup]").controlgroup().controlgroup("refresh");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error Q001!");
},
}); // ### AJAX to get ALL AREAS on page load ###
}); // ### document.on
The alerts in the loop are just to see what's happening inside. The textToInsert is built correctly, but then append is missing out on last two elements.
I've tried to append inside the loop but that made no difference to the outcome. Please help.
You are incrementing your counter too soon. Instead of ++i, try i++
for (i = 0; i <= all_areas.length; i++) {
var area = JSON.stringify(all_areas[i][0]);
alert(area + i);
textToInsert += '<input type="radio" class="all-areas" name="property-area" id="' + area + '" value="' + area + '"><label for="' + area + '">' + area + '</label>';
alert(textToInsert);
}
If using for loop like this:
You are using i < all_areas.length because variable i strats from 0 so you can use i <= all_areas.length;
and also ++i you write pre increment; you can use post increment i++ then you can get all the radio buttons..

How to style dynamically generated Select2 dropdowns after the page has loaded?

I am using Select2 for dropdown styling from http://ivaynberg.github.io/select2/ .
I have several dropdowns on the page which are styled correctly using the following:
<script>
$(document).ready(function() {
$("#dropdown1").select2();
$("#dropdown2").select2();
});
</script>
Now, I have another option on the page where it allows the user to add as many dropdowns as they want for additional options, the following way:
<img src="images/add.png" title="Add Row" border="0" onclick="addRowToCountryPrice('',''); return false;">
<input type="hidden" name="TotalLinesCountry" id="TotalLinesCountry">
<script>
var arr = new Array();
var ind=0;
function showCountryDrop(name1,sel, param){
var dval="";
dval = "<select name=\"" + name1 + "\" id=\"" + name1 + "\" class=\"countriesclass\">";
dval += "<option value=\"\">Select Country</option>\r\n";
selVal = (sel==0001) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0001\" " + selVal + ">United Kingdom</option>";
selVal = (sel==0002) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0002\" " + selVal + ">United States</option>";
selVal = (sel==0003) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0003\" " + selVal + ">Albania</option>";
selVal = (sel==0004) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0004\" " + selVal + ">Algeria</option>";
dval +="</select>";
return dval;
}
function addRowToCountryPrice(country,price) {
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var cellVal = "";
var cellLeft;
var i=0;
arr[ind] = (iteration+1);
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = showCountryDrop("countryDrop_" + ind,country);
cellLeft = row.insertCell(i++);
var price = (price!=0) ? price : "0.00";
cellLeft.innerHTML = "<input type=\"text\" name=\"countryPrice_" + ind + "\" id=\"countryPrice_" + iteration + "\" value = \"" + price + "\" size=\"8\">";
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = "<img src=\"images/delete.png\" title=\"Delete Row\" border=\"0\" onclick=\" removeRowFromTable(" + ind + "); return false;\">";
document.getElementById("TotalLinesCountry").value = (parseInt(ind)+1);
ind++;
}
function removeRowFromTable(src)
{
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
if (arr[src]!="") tbl.deleteRow((arr[src]-1));
arr[src]="";
var counter = 1;
for( i=0; i<arr.length; i++) {
if (arr[i]!="") {
arr[i]= counter;
counter++;
}
}
return false;
}
</script>
While it generates the dropdowns correctly, they are not styled through the class "countriesclass", even if I do a:
$(".countriesclass").select2();
I also tried
dval +="</select>";
$(".countriesclass").select2();
return dval;
And that seems to be PARTIALLY working in a strange way. When I create the first dropdown, it doesn't get styled. When I create another second dropdown, then the first one gets styled but the second one doesn't. It then doesn't let me create further ones and shows an error.
Any ideas how I could get this working?
UPDATE: jsFiddle http://jsfiddle.net/y6af098z/2/
Your call to $('.countriesclass') goes off when the document is ready. But the select has not been added to the document yet, then. So no elements are found.
You should look up the added select after the user has clicked on the plus and you've added the select to the dom.
$('#plus').on('click', function () {
$tr = addRowToCountryPrice('Algeria', 0);
$('.countriesclass', $tr).select2();
});
The second argument $tr tells jquery only to look in the recently added table row, so that you only select the newly added select which is a child of the newly added tr. Not the selects in the other rows.
Like #dreamweiver already noted, you should make better use of jquery when creating the dom elements. That's what jquery is good at. I've updated the jsfiddle to show how you can create the select and table row the jquery way.
DEMO
Instead of using getelementbyId use getelementbyClass and give each dropdown a class, you can only have one getelementbyid.
Hope this helps. if you want i could send you the code for what you require?
The select2 when called was not able to find the dropdown list boxes,because they were added dynamically and hence the those were not visible for the jQuery class selector $(".countriesclass").select2();.
This type of behaviour can be overcome by referencing the selector from the document element, rather than referring the element directly like above. so the new selector should be like this
$(document).find("select.countriesclass").select2();
Also I have done few tunings in your code.
Live demo:
http://jsfiddle.net/dreamweiver/y6af098z/8/
Note: one more thing, when using jQuery lib make sure you make the most of it, don't use raw JS code instead use the jQuery equivalent syntax for the same, which would be simple and easy to use.

Javascript generating content from an array on user search

I'm having issues dynamically creating content from an array of images. What I want to happen is that when keywords are entered into the searchbar (try "joyride" or "nick"), all of the images that match the keywords show up. Currently, only one image shows up, and it doesn't necessarily match the keyword. I think I'm going wrong with the javascript function - I feel like I shouldn't be using innerHTML to create the photos, especially because when the keyword is deleted, it just leaves the one image.
Would it be easier to do it all in jQuery/javascript, instead of generating the initial gallery of images in jQuery and trying to do the filtering in javascript? I'm lost.
http://scf.usc.edu/~uota/itp301/final/odc-photos.html
This is a working version of the page, with the arrays and other code that I am using.
Thanks in advance!
$(document).ready(function(){
for(var i = 0; i < src.length; i++){
var content = "<div class='pics' id='imagesection" + i + "'>";
content += "<div class='images'><img class='imagesfiles' height='133px' width='200px' src='" + src[i] + "'></div>";
content += "</div>";
$("#gallery").append(content).hide().fadeIn(250);
}
});
var songSearch = function(keyword){
var foundFlag = false;
var content = "";
for (var i = 0; i < src.length; i++){
if (tags[i].toLowerCase().indexOf(keyword) != -1 || keyword == "") {
content = "<div class='pics' id='imagesection" + i + "'>";
content += "<div class='images'><img class='imagesfiles' height='133px' width='200px' src='" + src[i] + "'></div>";
content += "</div>";
findFlag = true;
}
}
if(findFlag){
document.getElementById("gallery").innerHTML = content;
}
else{
content = "Your search did not return any results.";
}
}
</script>
It looks like the problem is on this line in the songSearch function:
content = "<div class='pics' id='imagesection" + i + "'>";
You are redefining the variable content instead of concatenating it. This way it will always be just the last image. Try changing it to:
content += "<div class='pics' id='imagesection" + i + "'>";
There is also have a variable inside the songSearch function called foundFlag that is later referenced as findFlag. That shouldn't be causing the issue though.

html table editable and non-editable cells with jQuery

Is there a plugin or way to make certain table columns (not rows) editable and others not editable
with jQuery?
I have seen plugins for clicking on a cell to make it editable, but I mean explicitly making a cell/column editable or not.
I have a way of doing it but it feels like a bit of a hack job.
Here is my function for making a column editable:
function isEditable(rowArray, headersArray)
{
var counter = 0;
var notEditable = ['product code', 'product'];
for(i in rowArray){
counter = 0;
data = headersArray[i].toLowerCase();
for(a in notEditable){
if(data == notEditable[a]){
counter++;
}
}
if(counter > 0){
rowArray[i] += 'notEditable';
}
}
return rowArray;
}
it compares the header of the cell to an array of predefined values which = a non-editable column.
Then I build the row:
function buildHTMLTableRow(row, mutable)
{
output = '';
output += '<tr>';
for(var i = 0; i < row.length; i++)
{
value = trim(row[i]);
if(mutable){
index = value.indexOf('notEditable');
if(index != -1){
value = value.substring(0, index);
output += '<td>' + value + '</td>';
}
else{
output += '<td><input size="5" type="text" value="' + value + '" /></td>';
}
}
else{
output += '<td>' + value + '</td>';
}
}
output += '</tr>';
return output;
}
The mutable parameter decides if the row is editable or not, and the indexOf('noteditable') decides for the cell(but pretty much column) from the isEditable function.
Is there a plugin that does this better, or should I just settle with what I have?
Visit this jsFiddle link: Disable Columns
Following is the data flow:
I have created a row Array named "rowsD". When page loads I am populating my table (id=myData) with these rows.
Now creating another array called disableHeaders wherein I am passing the headers,
which you need to disable entire columns.
I am calling function disableFields passing disableHeaders as parameter
In the function, first I am fetching the index of the header whose value is equal to the values in headers array
If I find one, then from Input tag I am extracting the Value attribute using $(this).find('input') selector
Finally I am replacing the current child with Label tag passing the extracted Input tags Value
You may also comment out disableFields(disableHeaders); line to actually see, how table gets rendered initially
Thank you

Categories

Resources