I just got a problem about this response. Supposedly if I want to choose item from the response it must be an array value.
"telegraphicTransferBankMap": {
"BOA BEJ, JKT": "0330301",
"BPD KALBAR SYARIAH, PTK": "1239922",
"ANDARA, DPSR": "4660019",
"GANESHA HAYAM WURUK, JKT": "1610017",
...
}
Actually must be like this one right? (let me know if I'm mistaken)
"telegraphicTransferBankMap": [
{"BOA BEJ, JKT": "0330301"},
{"BPD KALBAR SYARIAH, PTK": "1239922"},
{"ANDARA, DPSR": "4660019"},
{"GANESHA HAYAM WURUK, JKT": "1610017"},
...
]
My code:
var ul = $('#telegraphicTransferBankMap');
var html ='';
for (var key in telegraphicTransferBankMap) {
if (telegraphicTransferBankMap.hasOwnProperty(key)) {
telegraphicTransferBankMapItem = telegraphicTransferBankMap[key];
html += '<option value="'+telegraphicTransferBankMapItem.xxxxxx+'">'+telegraphicTransferBankMapItem.yyyyyyy+'</option>';
}
}
ul.append(html);
Then I want to put telegraphicTransferBankMapItem.xxxxxx as bankId and telegraphicTransferBankMapItem.yyyyyyy as bankName.
Use your first json and change your loop like,
var telegraphicTransferBankMap = {
"BOA BEJ, JKT": "0330301",
"BPD KALBAR SYARIAH, PTK": "1239922",
"ANDARA, DPSR": "4660019",
"GANESHA HAYAM WURUK, JKT": "1610017",
}
for (var key in telegraphicTransferBankMap) {
if (telegraphicTransferBankMap.hasOwnProperty(key)) {
bank = telegraphicTransferBankMap[key];
html += '<option value="' + bank + '">' + key + '</option>';
}
}
Live Demo
Also you should bank-id as key in your json rather than of bank name.
As of your code here:
if (telegraphicTransferBankMap.hasOwnProperty(key)) {
telegraphicTransferBankMapItem = telegraphicTransferBankMap[key];
an object like your first definition is expected - and sufficient
To add that to the option list just do
html += '<option value="'+key+'">'+telegraphicTransferBankMapItem+'</option>';
Related
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.
I have a couple of inputs like so:
<input name="education[1][yearbegin]" type="date" class="form-control">
<input name="education[2][yearbegin]" type="date" class="form-control">
The data is sent to my server to be verified, and if it's invalid it sends back data like so:
{
"education.0.institution":["The education.0.institution field is required."],
"education.0.degree":["The education.0.degree field is required."]
}
I don't always get more than 1 back, sometimes it could be many I am trying to loop over to append an error to the input like so:
var errors = $.parseJSON(data.responseText);
alertHtml += '<ul>';
$.each(errors, function (key, value) {
$('.form-control[name=' + key + ']').closest('.form-group').addClass('has-error');
alertHtml += '<li>' + value + '</li>';
});
alertHtml += "</ul>";
This doesn't work though, because it's trying to find the input name of:
education.1.yearbegin
Rather than
education[1]yearbegin
My inputs won't always be arrayed, but the ones that are don't append How can I append the error message to the input by changing the javascript? The json is being sent back by Laravel's array validation
It's unfortunate that the server accepts the names in one form but sends them back in another.
If we assume that dot syntax should always be converted to brackets syntax, it's fairly straightforward to update the keys:
var updated = key.split(".");
if (updated.length == 1) {
updated = updated[0];
} else {
updated = updated[0] + "[" + updated.slice(1).join("][") + "]";
}
For multi-part keys, that inserts [ before the second and ][ in-between the second and third, third and fourth, etc.; and adds ] at the end.
Example:
var errors = [
{"education.1.yearbegin":["The education.1.yearbegin field is required."]},
{"education.2.yearbegin":["The education.2.yearbegin field is required."]}
];
errors.forEach(function(error) {
Object.keys(error).forEach(function(key) {
var updated = key.split(".");
if (updated.length == 1) {
updated = updated[0];
} else {
updated = updated[0] + "[" + updated.slice(1).join("][") + "]";
}
console.log("Original: " + key + ", updated: " + updated);
});
});
If you're also struggling with showing all of the errors in the array next to the form control, you just loop through them. You're receiving an object where the property names in the object are the form control names, and the values are arrays of error messages. So we
Loop through the property names of that object, and for each property name:
Mark the relevant control, and
Loop through that entry's array of errors to append them to alertHtml.
Something long these lines:
var errors = {
"education.1.yearbegin":["The education.1.yearbegin field is required."],
"education.2.yearbegin":["The education.2.yearbegin field is required."]
};
function fixKey(key) {
var updated = key.split(".");
if (updated.length == 1) {
updated = updated[0];
} else {
updated = updated[0] + "[" + updated.slice(1).join("][") + "]";
}
return updated;
}
var alertHtml = '<ul>';
// #1: Loop through the object's property names
Object.keys(errors).forEach(function(key) {
// #2: Mark the control, using the corrected name
$('.form-control[name="' + fixKey(key) + '"]').closest('.form-group').addClass('has-error');
// #3: Loop through the errors
errors[key].forEach(function(msg) {
alertHtml += '<li>' + msg + '</li>';
});
});
alertHtml += "</ul>";
$(document.body).append(alertHtml);
.has-error {
border: 1px solid red;
}
<div class="form-group">
<input name="education[1][yearbegin]" type="date" class="form-control">
</div>
<div class="form-group">
<input name="education[2][yearbegin]" type="date" class="form-control">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The first issue with the name:
I would just change the name to something that's a bit easier to read rather then having it like:
name="education[1][yearbegin]"
Maybe have it like:
name="EducationYearBegin1"
For the second issue:
You could check if the property is an array, so like this:
if (value instanceof Array) {
value.forEach(function (item) {
alertHtml += '<li>' + item + '</li>';
})
} else {
alertHtml += '<li>' + value + '</li>';
}
Maybe something like that?
The foreach would cover you if you ever had multiple errors in your array too.
You can use String#replace to convert education.1.yearbegin to be education[1][yearbegin]
See fixName function in this code.
function fixName(name) {
var newName = name.replace(/\.\d\./, function ($1) {
return "[" + $1.replace(/\./g, "") + "]"
}).replace(/\].+/, function ($1) {
return $1.replace(/\]/, "][") + "]"
});
return newName;
}
var errors = [{"education.1.yearbegin":["The education.1.yearbegin field is required."]},
{"education.2.yearbegin":["The education.2.yearbegin field is required."]}]; //$.parseJSON(data.responseText);
var alertHtml = document.querySelector("#alert");
alertHtml.innerHTML += '<ul>';
$.each(errors, function (key, obj) {
var realKey = fixName(Object.keys(obj)[0]);
$('.form-control[name="'+ realKey +'"]').addClass('has-error');
alertHtml.innerHTML += '<li>' + obj[Object.keys(obj)[0]][0] + '</li>';
});
alertHtml.innerHTML += "</ul>";
.has-error {
color: red;
}
li {
color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="education[1][yearbegin]" type="date" class="form-control">
<input name="education[2][yearbegin]" type="date" class="form-control">
<div id="alert"></div>
I am making a program, and I'm wondering why all I see on my html page is the form, but only a single . where the bulleted list for an unordered list should be. I input the user input in the fields, but it doesn't show me the data in the fields, like it's supposed to, when I click submit. Here's the code.
function getFormElements() {
var gather_form_elements = new Array(
$("#first_name").val(),
$("#last_name").val(),
$("email").val(),
$("#phone_number").val()
);
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
for(i=0; i<gather_form_elements.length; i++)
{
document.getElementById("contact_info").innerHTML = "<li>" + gather_form_elements[i] + "</li>";
}
}
Because you are overiding it on every iteration. Try to accumulate the html before using innerHTML like this:
var html = "";
for(var i = 0; i < gather_form_elements.length; i++) {
html += "<li>" + gather_form_elements[i] + "</li>";
// ^^ the += is crucial. If you don't use it, it will just replace the content of html (the innerHTML in your code), we need to use += to append to html instead of overriding it.
}
document.getElementById("contact_info").innerHTML = html;
You can acheive the same result using only one line of code:
document.getElementById("contact_info").innerHTML =
'<li>' + gather_form_elements.join('</li><li>') + '</li>';
So I got a loop of processes. You can check it here.
So the point is my system can have different number of processes. And for each process there can be more than one studio. What I want to achieve is to save studios under one process into one array cell divided by coma. So later I could use this array and split studios to insert it to database.
My save function:
var LISTOBJ = {
saveList: function() {
$(".output").html("");
$(".studio").each(function() {
var listCSV = [];
$(this).find("input").each(function() {
listCSV.push($(this).text());
});
var values = '' + listCSV.join(',') + '';
$(".output").append("<input type='text' name='studio[]' value='" + values + "' />");
$("#output").append("<p>" + values + "</p>");
console.debug(listCSV);
});
}
}
But it seems it doesnt work. What do I need to change to achieve what i want? Thank you
on html file, on process 1 select option add this to the class attribute process-1, and on the process 2 also add process-2 on class attribute then, modify the saveList function
var processList = {process_1 : [] , process_2 : []};
$(".output").html("");
$(".studio").each(function() {
var text = $(this).val();
var process1 = $(this).hasClass('process-1');
var process2 = $(this).hasClass('process-2');
if(text) {
listCSV.push(text);
if(process1) {
processList.process_1.push(text);
} else if (process2) {
processList.process_2.push(text);
}
}
});
listObj.saveList = listCSV;
var values = listCSV.join(', ');
$(".output").append("<input type='text' name='studio[]' value='" + values + "' />");
$("#output").append("<p>" + values + "</p>");
console.log(processList);
ahh, i think i have solved the first question, about the question #1. on your html file add value attribute on each option. and also remove the div class="studio" hence put the class "studio" on the select class. after that try my code on the javascript file
// everytime the save button is clicked
$('#savebutton').click(function() {
saveList();
});
// set list studio
var listCSV = [];
// your list object
var listObj = {saveList: []};
// save list function
function saveList() {
$(".output").html("");
$(".studio").each(function() {
var text = $(this).val();
if(text) {
listCSV.push(text);
}
});
listObj.saveList = listCSV;
var values = listCSV.join(', ');
$(".output").append("<input type='text' name='studio[]' value='" + values + "' />");
$("#output").append("<p>" + values + "</p>");
}
I'm using
http://davidstutz.github.io/bootstrap-multiselect/ for creating bootstrap multiselect controls in my webpage.
The below fiddle link with static data is what I want to achieve using dynamic data:
https://jsfiddle.net/DROCKS/mrmLrsad/4/
//please refer the fiddle
The search option works fine in case the values of the select box are static, but if they are dynamically created, the multiselect gets created. However the search filter is not working in this case. However the my code is similar to the fiddle below, the only difference being that the search filter part doesn't work in my actual code, but works in this fiddle.
fiddle link with dynamic data.
https://jsfiddle.net/DROCKS/mrmLrsad/5/
//please refer the fiddle
This is my code.
HTML code
<select id="lstFieldList" ></select>
jQuery code [Updated]:
function uncheckFields(field_id)
{
$('#' + field_id).multiselect('deselectAll', true);
}
//json_obj is the value from the fiddle.
createMultiSelectBox(json_obj);
//this function creates the multiselect
function createMultiSelectBox(json_obj)
{
var element_String = "";
var default_ele_set = 0;
var def_element_first = "1"; //if the first Y flag should be considered
var def_element_last = "n"; //if the last Y flag should be considered
var def_element = def_element_first; //change the value here to toggle between default selection
var tmp = [];
for (var key in json_obj)
{
var val = json_obj[key];
//alert("Key: " + key);
var chk_box_ctr = 0;
var element;
for(var child_key in val)
{
//alert("key: " + child_key + "\nvalue: " + val[child_key]);
var default_value = child_key.split(",")[7];
//alert("default_value: " + default_value);
if(!chk_box_ctr)
{
g_max_PageSize = child_key.split(",")[8];
//alert("g_max_PageSize: " + g_max_PageSize);
}
if(def_element == def_element_first)
{
if(default_value == "Y" && !default_ele_set)
{
//element_String += '<option value="' + child_key + '" selected="selected">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
else
{
//element_String += '<option value="' + child_key + '">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
}
else
{
if(default_value == "Y")
{
//element_String += '<option value="' + child_key + '" selected="selected">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
else
{
//element_String += '<option value="' + child_key + '">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
}
tmp.push(element);
}
if(def_element == def_element_last)
{
uncheckFields('lstFieldList');
}
}
//$('#lstFieldList').append(element_String);
//$('#lstFieldList').multiselect('rebuild');
$("#lstFieldList").multiselect('dataprovider', tmp);
$('#lstFieldList').multiselect({
maxHeight: 200,
buttonWidth:"100%",
enableFiltering:true,
enableCaseInsensitiveFiltering:true,
/*maxHeight: 200,
enableCaseInsensitiveFiltering: true,
//enableFiltering: true,
onChange: function(option, checked, select) {
alert('Changed option ' + $(option).val() + '.' + "\nchecked: " + checked + "\nselect: " + select);
if(checked)
{
//uncheckFields('lstFieldList');
}
else
{
uncheckFields('lstFieldList');
}
}*/
});
var elem = $('#lstFieldList').next();
elem.attr('class',(elem.attr('class') + ' open'));
}
What could be the problem? because the same code is present in both the files.
Any help would be appreciated.
Thanks in advance.
create an array var tmp = [];
create a json like this while looping for option
element = {"label": this.Name,"value":this.id};
and push each element to tmp
tmp.push(element);
and pass this tmp array to multi select
$("#lstFieldList").multiselect('dataprovider', tmp);
and add multiselect to dropdown by
$("#lstFieldList").multiselect({
maxHeight: 260,
buttonWidth:"100%",
enableFiltering:true,
enableCaseInsensitiveFiltering:true,
});
I actually found out what was causing the unusual behavior in the code related to the bootstrap multiselect plugin. The code given to me by Anoop was right, I also tried various different codes related to the same plugin in the past months, but I later drop the idea to use the plugin.
Then lately last week while reworking on the same code, I identified that I had included some js script files in my html page. So I tried commenting out each include statement for the files in my html to identify which one was causing the issue. So on doing so I reached at a particular js file.
Once the file was identified, I just needed to find out which function was causing the problem to the suggestion logic of the plugin. So to identify this, I kept on commenting/removing the functions till I arrived to the function that caused the issue. There was a code related to window.setTimeout. It was due to this function that the existing suggestion logic was not working as the code was coming into this block. So I later added some flagging logic to avoid running this function in my case.
Thanks a lot all for your inputs.....