How to dymically update object on input change? - javascript

I have a input tab that I want to update dynamically. When the user changes the value of the input, the new value should replace the old value of the object inside the array.
I am way off the mark here. Can somebody help me out.
function Skills () {
var Skills = this;
this.skill = new Array();
this.skill[0] = {
id: '1_skill_field',
value: 'Insert Skill',
//change function to be used when user changes the value.
change:function (input) {
Skills.skill[parseInt(input.id)["value"]=$("#"+input.id).val();
}
}
var create_section_field = function () {
var section_field = $('<div class="section_fields"></div>');
section_field.appendTo('#skill');
}
var create_fields = function () {
var input_field = $('<div class="input_fields"></div>');
input_field.appendTo('#skill .section_fields');
var skill_field=$('<input>', {
name: '1_skill_field',
id: Skills.skill[0]["id"],
value: Skills.skill[0]["value"],
type: 'text',
//onChange uses function to change saved value of object inside array
onChange: Skills.skill[0].change(this)
});
skill_field.appendTo($('#skill .input_fields'));
}
}

i made what you were doing...here take a look:
http://jsfiddle.net/V4HLz/1/
it was kinda fun. :D
var type = $('#type'),
input = $('#input'),
btn = $('#update'),
show = $('#out'),
stats = $('.skills');
var value, sType, skills={};
btn.click(function(){
value = parseFloat(input.val().trim());
sType = type.val();
if (!value || !sType) return;
skills.update(sType,value);
updateInput();
});
type.change(updateInput);
function updateInput() {
input.val(skills.data[type.val()]);
}
skills.update = function(t,v){ this.data[t] = v; };
skills.data = {
eating:0,
fighting:0,
flying:0,
reg:0
};
show.click(function(){
$.each( skills.data, function(k,v){
stats.find('#'+k).children('span').text(v);
});
});

Related

servicenow integrations problem with while

i have a problem, I am trying to take the value of a field of the users table that I populated in the first while, but when I try to take the value in the second while of the second call, it returns 0, I cannot understand why, the values ​​in the field are populated.
my code below:
var r = new sn_ws.RESTMessageV2('success_factors_api', 'GET');
var response = r.execute();
var reviver = function(key, value) {
if (typeof value === 'undefined') {
return null;
}
};
var responseBody = JSON.parse(response.getBody(), reviver());
var httpStatus = response.getStatusCode();
//gs.info(responseBody.d.results[0].nationalId);
var gr = new GlideRecord('sys_user');
gr.addEncodedQuery('u_codice_fiscaleISNOTEMPTY');
gr.query();
while (gr.next()) {
var fiscalCode = gr.getValue('u_codice_fiscale');
responseBody.d.results.forEach(function(obj) {
if (fiscalCode === obj.nationalId) {
gr.u_personal_id_external_successfactor = obj.personIdExternal;
gr.update();
}
});
}
var r2 = new sn_ws.RESTMessageV2('success_factors_api', 'GETEMPLOYMENT');
var response2 = r2.execute();
var reviver2 = function(key, value) {
if (typeof value === 'undefined') {
return null;
}
};
var responseBody2 = JSON.parse(response2.getBody(), reviver2());
var httpStatus2 = response2.getStatusCode();
gr.addEncodedQuery('u_personal_id_external_successfactorISNOTEMPTY');
while (gr.next()) {
var personalIdExternal = gr.getValue('u_personal_id_external_successfactor');
gs.info(personalIdExternal); //return me 0
responseBody2.d.results.forEach(function(obj) {
if (personalIdExternal === obj.personIdExternal) {
gr.u_user_id_successfactor = obj.userId;
gr.update();
}
});
}
Your second loop is missing a gr.query(). Also, you should never reuse a GlideRecord like that. Declare a new GlideRecord for the second loop.

Sum object values

I'm trying to sum the values from the key "value" in the object data.
Googled alot but cant figure this out.
My guess is that i'm not retrieving the values from localStorage.
EDIT: And i want to save the summed values to localStorage...
var storage = localStorage.getItem("Bills");
if (storage !== null) {
var data = JSON.parse(storage);
loadData(data);
var id = data.length;
} else {
id = 0;
data = [];
};
function loadData(array) {
array.forEach(function(bill) {
newItem(bill.name, bill.value, bill.id, bill.payed);
});
};
function addBill() {
modal.style.display = "none";
var bill = document.getElementById("billName").value;
var billVal = document.getElementById("billValue").value;
newItem(bill, billVal, id, false);
data.push({
name: bill,
value: billVal,
id: id,
payed: false
});
billsTotals.innerHTML = Object.values(data).reduce((t, { value }) => t + value, 0); // ?????
localStorage.setItem("Bills", JSON.stringify(data));
};
function newItem(name, value, id, payed) {
if (payed == true) {
return;
}
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name + " " + value + "kr"));
li.setAttribute("id", id);
ul.appendChild(li);
bill = document.getElementById("billName").value = "";
billVal = document.getElementById("billValue").value = "";
};
i'v tried to add .values before reduce but nothing works:
billsTotals.innerHTML = Object.values(data.value).reduce((t, {value}) => t + value, 0); // ?????
Not sure about your data variable. But the data variable is an array then you could do something like this.
data.reduce((total,{value})=>{
return total +value
},0)

SharePoint 2013 list column title modification with javascript

I want to modify SharePoint 2013 list column title in views with javascript. There is a code I found here at stackoverflow, but I want to reference the column with the display name / internal name, not with the column position.
(function () {
function preTaskFormRenderer(renderCtx) {
modifyHeaderData(renderCtx);
}
function modifyHeaderData(renderCtx)
{
var viewTitle = renderCtx.viewTitle;
var linkTitleField = renderCtx.ListSchema.Field[1];
linkTitleField.DisplayName = viewTitle + ':' + linkTitleField.DisplayName;
}
function registerRenderer()
{
var ctxForm = {};
ctxForm.Templates = {};
ctxForm.OnPreRender = preTaskFormRenderer;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctxForm);
}
ExecuteOrDelayUntilScriptLoaded(registerRenderer, 'clienttemplates.js');
})();
Example:
SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function() {
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
OnPreRender: function(ctx) {
var field = getFieldByDisplayName(ctx,"Task Name");
if(field)
field.DisplayName = "Task Name:::";
}
});
});
function getFieldByDisplayName(ctx,name)
{
var result = ctx.ListSchema.Field.filter(function(f){return f.DisplayName == name;} ); //find field by display name
return result.length > 0 ? result[0] : null;
}
Result

Dynamically expanding table from object array

As the title states, I'm trying to create a table that will dynamically expand or shrink depending on the number of objects in the array. Each of these objects has 10 properties which all need to be displayed in separate rows. I started writing the for loop to iterate over the array and display each property using JQuery's .html() and realized it would look messy when all said and done, but I do not know where to start.. The complete code is below, but I'm working in the showResults function now..
//scripts
//Customer Object constructor
function CustomerObject(fName, lName, mName, address, city, state, zip, age, gender, pizza) {
this.fName = fName;
this.lName = lName;
this.mName = mName;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.age = age;
this.gender = gender;
this.pizza = pizza;
}
//Array of CustomerObjest
var CustomerArray = new Array();
$(document).ready(function () {
$("#TBFName").focus();
});
$("#BtnSave").click(function () {
//When Save button is pressed.
Validate();
});
$("#BtnReset").click(function () {
//When Clear button is pressed
ClearAllInfo();
});
$("#BtnDone").click(function () {
//When Done button is pressed
ShowResults();
});
$("#BtnMore").click(function () {
//When Enter More button is pressed
ShowResults();
$("#DivFormContainer").show();
$("#DivResults").hide();
});
$("#BtnMoreClearCustomers").click(function () {
//When Clear All Customers button is pressed
CustomerArray = new Array();
$("#DivFormContainer").show();
$("#DivResults").hide();
});
function Validate() {
var isValid = true;
var fstName = $("#TBFName").val();
var mdlName = $("#TBMI").val();
var lstName = $("#TBLName").val();
var addrs = $("#TBAdress").val();
var cit = $("#TBCity").val();
var stat = $("#DDState").val();
var zipCode = $("#TBZip").val();
var gend = $("input:radio[name='RGGender']:checked").val();
var old = $("#TBAge").val();
var pza = $("input:radio[name='RGLikePizza']:checked").val();
// Validation goes Here for All Fields
if (isValid == true) { //If isValid is still true, no errors
CustomerArray.push(new CustomerObject(fstName, lstName, mdlName, addrs, cit, stat, zipCode, old, gend, pza));
$("#DivMessage").show();
$("#DivMessage").html("Record Saved. Add a new record or press done to see results.");
$("#DivMessage").fadeOut(1600);
}
}
function ShowResults() {
ClearAllInfo();
$("#DivResults").show();
$("#DivFormContainer").hide();
//Code to display all customers information
for (var i = 0; i < CustomerArray.length; i++) {
$("#list").html(CustomerArray[i].fName + CustomerArray[i].lName + CustomerArray[i].mName);
//create table?
}
}
function ClearResultsDiv() {
$("#DivResults").html("");
}
function ClearAllInfo() {
$("input[type=text]").val("");
$("textarea").val("");
$("select").prop('selectedIndex', 0);
$(".error").html("");
$("input[type=radio]").attr('checked', false);
}
This is where direct DOM manipulation becomes messy and you are better off using an MVC framework. There are many to choose from: http://todomvc.com
I made a quick example using AngularJS:
http://codepen.io/anon/pen/nuGwz?editors=101
The nice thing is, you then only need to care about modifying your data (the customer array). The view (DOM) gets updated automatically. Like so:
$scope.CustomerArray.push({name: 'Joanna', age: '46', city: 'New York'});
As I understand it, you want to generate a table from an array containing row data.
Here's one way to make a table:
var maketable = (function(){
var elem, td, th, tr;
elem = function(elemtype, children){
var el = document.createElement(elemtype);
children.forEach(function(child){
el.appendChild(child);
});
return el;
};
td = function(s){
return elem('td', [document.createTextNode(s)]);
};
th = function(s){
return elem('th', [document.createTextNode(s)]);
};
tr = function(row){
return elem('tr', row.map(td));
};
return function(data){
var cols, rows, thead, tbody, table;
cols = Object.keys(data[0]);
rows = data.map(function(row){
return Object.keys(data[0]).map(function(key){
return row[key];
});
});
thead = elem('thead', [elem('tr', cols.map(th))]);
tbody = elem('tbody', rows.map(tr));
table = elem('table', [thead, tbody]);
return table;
};
}());
Example usage:
var data = [{a: 'a0', b: 'b0'}, {a: 'a1', b: 'b1'}, {a: 'a2', b: 'b2'}];
var table = maketable(data);
document.body.appendChild(table);

Cannot search multiselect after modification

I have 2 multi selects in a page, and I need to transfer some of the option in first into second, while mantaining the search capabilities.
The problem is, that when I use the search input, it restores the selects to their original options...
Here is the jquery search function:
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
Here is the js fiddle : http://jsfiddle.net/C2XXR/ !
*I believe the problem lies in the options variable, but have no idea on how to solve it *
Thanks!
I have updated the fiddle. http://jsfiddle.net/C2XXR/2/
I have updated the code for right and left transfer. You have to change the option array itself got the filter, adding them in the dom will not work. In the changed code one issue is once we add from right to left or left to right it is getting added in the last position of the target select.
Please check and let me know if this is what you want.
Below is the main changed function. Later you can create a common function i suppose. Code can be optimized more.
$('[id^=\"btnRight\"]').click(function (e) {
var selected = $(this).parent().prev('select');
var target = $(this).parent().next('select');
target.find('option[value="999"]').remove()
var options = selected.data('options');
var selectedVal = selected.find('option:selected').val()
var tempOption = [];
$.each(options, function(i) {
var option = options[i];
if(option.value != selectedVal) {
tempOption.push(option);
}
});
var targetOptions = target.data('options');
targetOptions.push({value: selected.find('option:selected').val(), text: selected.find('option:selected').text()});
target.data('options', targetOptions);
selected.find('option:selected').remove().appendTo('#isselect_code');
selected.data('options', tempOption);
});
$('[id^=\"btnLeft\"]').click(function (e) {
var selected = $(this).parent().next('select');
var target = $(this).parent().prev('select');
var options = selected.data('options');
var selectedVal = selected.find('option:selected').val()
var tempOption = [];
$.each(options, function(i) {
var option = options[i];
if(option.value != selectedVal) {
tempOption.push(option);
}
});
if( tempOption.length == 0 )
{
// add 999 here
}
var targetOptions = target.data('options');
targetOptions.push({value: selected.find('option:selected').val(), text: selected.find('option:selected').text()});
target.data('options', targetOptions);
selected.find('option:selected').remove().appendTo('#canselect_code');;
selected.data('options', tempOption);
});
the problem with your code is that after you click btnRight or btnLeft your collection of options for each select is not updated, so try after click on each button to call your filterByText as the following :
$('[id^=\"btnRight\"]').click(function (e) {
$(this).parent().next('select').find('option[value="999"]').remove()
$(this).parent().prev('select').find('option:selected').remove().appendTo('#isselect_code');
$('#canselect_code').filterByText($('#textbox'), true);
$('#isselect_code').filterByText($('#textbox1'), true)
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).parent().next('select').find('option:selected').remove().appendTo('#canselect_code');
$('#canselect_code').filterByText($('#textbox'), true);
$('#isselect_code').filterByText($('#textbox1'), true)
});

Categories