Label allow user input - javascript

I am creating a text box programmatically, but the problem that I am facing is that when I am inserting it in an array as an object to be vied on top of a list, the allowed type is label. Hence when the text box is displayed, the program does not allow the text box for user input. Is there a way to fix this? I have already tried to change the type to text and I get undefined.
searchArray = [];
//creating the text box and placing it in a variable
var textBox = "<input type='text' placeholder='Search Client Code'>";
searchArray.push({label: textBox });
//diaplaying the text box in a context menu sub menu
return{
"Search" : {
label : "Search",
action: true,
"submenu": searchArray,
disabled: false
}
}
*****************************************************
UPDATE
var searchArray = [];
var textBox = "<input type='text' placeholder='Search Client Code'>";
textBox.push({label: something});
//this array is used to insert the textbox and also the clients afterwards
new_array = [];
new_array.push(searchArray[0]);
//the below push is used in a for loop that loops each client,
//so I am just putting it here just for reference
***
new_array.push(itemDisp[i]);
***
if(...){
var obj = {
"DuplicateFor" : {
label : "Duplicate for",
action: true,
"submenu": new_array,
disabled: false
}
}
document.body.innerHTML = obj['DuplicateFor']['submenu'][0].label
}

Try this. It will create the input successfully and it takes input as well
var searchArray = [];
//creating the text box and placing it in a variable
var textBox = "<input type='text' placeholder='Search Client Code'>";
searchArray.push({
label: textBox
});
//diaplaying the text box in a context menu sub menu
var obj = {
"Search": {
label: "Search",
action: true,
"submenu": searchArray,
disabled: false
}
}
console.log(obj)
document.body.innerHTML = obj['Search']['submenu'][0].label

Related

How to use tabulator list editor together with html formatter?

I have options defined by id, label, description, e.g.
id
label
description
1
foo
foo_description
2
baa
baa_description
And would like to use them in a tabulator column.
The label should be used for display
The description should be shown as hover title of the label.
The id should be used when getting data from the table with getData()
I tried to use a list editor in combination with a html cell formatter for a column.
It kind of works. If I hover over a cell in the table, I can see a hover title. And hover titles
are shown for the options in the list/select editor, too.
However, when opening the list editor, the currently selected value is not shown as html foo any more but as text <span title=...>foo.
After closing the editor, the cell is shown correctly again.
=> How can I format the currently selected value of the list editor?
=> Or how should I otherwise define a tabular column to fulfills my needs?
I also tried to use an item formatter for the list editor to show html titles. That works inside the list editor but the table cell does not show a tool tip.
I could solve it with a combination of
custom cell formatter for the table
custom item formatter for the list editor
custom object class used for the values
converting columns that include custom value objects to ids before returning the data
class SelectableValue {
constructor(id, label, description){
this._id = id;
this._label = label;
this._description = description;
}
toString(){
return '<span title="'+ this._description +'">' + this._label + '<span>';
}
get id(){
return this.id;
}
}
_createDefaultColumns(endUseItems){
let endUseColumn = {
title: "End Use",
field: "id_end_use",
editor: "list",
formatter: this._cellFormatter,
editorParams: {
values: endUseItems,
itemFormatter: this._optionFormatter,
valueToIdConverter: this._valueToIdConverter
}
};
const columns = [
endUseColumn,
{ title: 2020, field: "2020", editor: true },
{ title: 2025, field: "2025", editor: true },
{ title: 2030, field: "2030", editor: true },
];
return columns;
}
_valueToIdConverter(selectableValue){
//defines what data is returned from the table as
//replacement for the stored object / displayed label
return selectableValue.id;
}
_cellFormatter(cell, formatterParams, onRendered){
//defines how table cells are shown
let selectableValue = cell.getValue();
return selectableValue.toString();
}
_optionFormatter(label, selectableValue, item, element){
//defines how options of the cell editor are shown
return selectableValue.toString();
}
_endUseItems(){
let items = []
let endUseRows = this._context.endUses.rows
for (let row of endUseRows){
let id = row[0];
let label = row[1];
let description = row[2];
let value = new SelectableValue(id, label, description)
let item = {
'value': value, //Value stored in table; includes unique id
'label': label //Used as label for the currently selected item
//when cell editor is openend
}
items.push(item);
}
return items;
}
_convertValues(displayData, columns){
let data = structuredClone(displayData);
for (let column of columns){
let _valueToIdConverter = this._valueToIdConverter(column);
if(_valueToIdConverter){
let field = column.field;
for(let row of data){
let value = row[field];
let id = _valueToIdConverter(value);
row[field] = id;
}
}
}
return data;
}

Use a user input value instead of a parameter

I have this function which works perfectly while I enter parameters, but it's not what I need, so given the code below, how can I use a user input value instead of the parameter to search through the array and return the objects?
Please keep it as simple as possible,I'm new to javaScript.
Please include input and button as html fields as well.
carSelection = [{
manufacturer: "Fiat Automobiles S.p.A.",
type: "Fiat 500",
fuel: "Eurosuper 98",
condition: "New",
enginePower: "101kW"
},
{
manufacturer: "Kia Motors Corporation (KMC)",
type: "Kia Sportage",
fuel: "Euro Diesel",
condition: "Used",
enginePower: "185kW"
},
{
manufacturer: "BMW AG",
type: "BMW X5",
fuel: "Euro Diesel",
condition: "Used",
enginePower: "195kW"
},
{
manufacturer: "Toyota Motor Corporation ",
type: "Toyota Corolla",
fuel: "Eurosuper 95",
condition: "Used",
enginePower: "165kW"
}
];
var bmw = 'BMW X5';
// var n1 = bmw.indexOf("bmw", 0);
var toyota = 'Toyota Corolla';
var fiat = 'Fiat 500';
var kia = 'Kia Sportage';
var input = document.getElementById("input").value;
function findCar(arr, searchProp) {
var rezArr = [];
for (var i = 0; i < arr.length; i++) {
Object.keys(arr[i]).forEach(function(prop) {
if (arr[i][prop] === searchProp) {
rezArr.push(arr[i]);
}
})
}
return rezArr;
}
var item2 = findCar(carSelection, bmw);
console.log(item2);
<input id="input" type="text"/>
Your input html looks fine to me. You should add a button which would look something like <button id="button">.
Now, You'll want to add a click event listener to the button. This is basically a function that will be called whenever the button is clicked. There's a couple ways of adding the event listener but I think the best is
const button = document.getElementById('button'); //get a reference to the button element
button.addEventListener('click', handleClick) // specify a function that should be called whenever the button is clicked
function handleClick(){
var input = document.getElementById("input").value;//get the current value of the input
findCar(carSelection, input) //find the car
}
So whenever the button is clicked, we'll go get the current value of input and pass that to the function you've already written.
The reason your current code won't work is that you grab the value of input as soon as the script loads when, more than likely, the user hasn't had time to type anything into it yet. So it will always be an empty string ("").

JavaScript - Adding an object to the end of an array through a input field

I am trying to dynamically add an object with values from an input field to the end of an array using JavaScript. The only catch is that I'm trying to do it with an input field. Here's what I want to happen:
The user types in something in a text field
My program already adds a unique ID for it
Add it to the end of an array in the form of a object
Keep on adding objects to that array
This is what I want in my JSON file:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, {
"id": 1,
"description": "Task #2 Description"
}, {
"id": 3,
"description": "Task #3 Description"
}]
}
What I am currently getting is:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, ]
}
Every time I add a new Task, it replaces the one that is already there.
Here is my JavaScript code:
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.onclick = function() {
id = indentification++;
description = content.value;
var task = {
list: []
}
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
I would really appreciate it if anyone could help me out. I've spent hours trying to figure it out. Thanks!
The problem is here:
var task = {
list: []
}
task.list.push({id, description});
Each time you do this your list become empty then add new item.
change to this
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
var task = {
list: []
}
submit.onclick = function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8"); // what're you doing here, browser do not allow write file to disk
}
There are a couple of things that you need to consider here:
Form submit must be refreshing the page and resetting your global variables. Thus you need to prevent default action on click of submit.
(as mentioned in earlier answers) The list is being initiated on every click. You will need to initialize the variable task outside the onClick function
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
//initialize outside the on click function
var task = {
list: []
}
submit.onclick = function(e) {
//This prevents page refresh on form submission and preserves the global variable states
e.preventDefault();
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
This should hopefully solve your problem.
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.addEventHandler("click", function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}

Netsuite Saved Search to Suitelet Sublist

I am trying to populate a sublist in a suitelet with data from a custom saved search that I have already created. My problem is that the sublist is only populating data from fields that correspond to the "type" of saved search I am doing. For example, in this instance the saved search is a "transaction" type search. If, for example, I want to reference a customer field withing the saved search, say "Name" and "Billing Address", this data will not populate the sublist in the suitelet. All other fields that are being referenced in the Transaction record itself populate the sublist fine. I was just wondering if anyone has ever run into the same issue, anyways here's the code I'm trying to implement.
var form,
sublist;
//GET
if (request.getMethod() == 'GET')
{
//create form
form = nlapiCreateForm('Test Custom Suitelet Form', false);
//create sublist to show results
sublist = form.addSubList('custpage_sublist_id', 'list', 'Item List');
//form buttons
form.addSubmitButton('Submit');
form.addResetButton('Reset');
// run existing saved search
var searchResults = nlapiSearchRecord('transaction','customsearchID');
var columns = searchResults[0].getAllColumns();
// Add the search column names to the sublist field
for ( var i=0; i< columns.length; i++ )
{
sublist.addField(columns[i].getName() ,'text', columns[i].getLabel() );
nlapiLogExecution('DEBUG', 'Column Label',columns[i].getLabel());
}
//additional sublist fields
sublist.addMarkAllButtons();
sublist.addField('custfield_selected', 'checkbox', 'Selected');
sublist.setLineItemValues(searchResults)
response.writePage(form);
}
If you review the nlobjSublist docs you'll see that sublist.setLineItemValues can also take an array of hashes. What does work is:
function getJoinedName(col) {
var join = col.getJoin();
return join ? col.getName() + '__' + join : col.getName();
}
searchResults[0].getAllColumns().forEach(function(col) {
sublist.addField(getJoinedName(col), 'text', col.getLabel());
nlapiLogExecution('DEBUG', 'Column Label', col.getLabel());
});
var resolvedJoins = searchResults.map(function(sr) {
var ret = {
id: sr.getId()
};
sr.getAllColumns().forEach(function(col) {
ret[getJoinedName(col)] = sr.getText(col) || sr.getValue(col);
});
return ret;
});
sublist.setLineItemValues(resolvedJoins);

Remove node function on parent element

I'm new to JS. I'm trying to delete the parent node with all the children by clicking a button. But the console tells me that undefined is not a function. What am I missing?
Fiddle:
http://jsfiddle.net/vy0d8bqt/
HTML:
<button type="button" id="output">Get contacts</button>
<button type="button" id="clear_contacts">clear contact</button>
<div id="output_here"></div>
JS:
// contact book, getting data from JSON and outputting via a button
// define a JSON structure
var contacts = {
"friends" :
[
{
"name" : "name1",
"surname" : "surname1"
},
{
"name" : "name2",
"surname" : "surname2"
}
]
};
//get button ID and id of div where content will be shown
var get_contacts_btn = document.getElementById("output");
var output = document.getElementById("output_here");
var clear = document.getElementById("clear_contacts");
var i;
// get length of JSON
var contacts_length = contacts.friends.length;
get_contacts_btn.addEventListener('click', function(){
//console.log("clicked");
for(i = 0; i < contacts_length; i++){
var data = contacts.friends[i];
var name = data.name;
var surname = data.surname;
output.style.display = 'block';
output.innerHTML += "<p> name: " + name + "| surname: " + surname + "</p>";
}
});
//get Children of output div to remove them on clear button
//get output to clear
output_to_clear = document.getElementById("output_here");
clear.addEventListener('click', function(){
output_to_clear.removeNode(true);
});
You should use remove() instead of removeNode()
http://jsfiddle.net/vy0d8bqt/1/
However, this also removes the output_to_clear node itself. You can use output_to_clear.innerHTML = '' if you like to just delete all content of the node, but not removing the node itself (so you can click 'get contacts' button again after clearing it)
http://jsfiddle.net/vy0d8bqt/3/
You want this for broad support:
output_to_clear.parentNode.removeChild(output_to_clear);
Or this in modern browsers only:
output_to_clear.remove();
But either way, make sure you don't try to remove it after it has already been removed. Since you're caching the reference, that could be an issue, so this may be safer:
if (output_to_clear.parentNode != null) {
output_to_clear.remove();
}
If you were hoping to empty its content, then do this:
while (output_to_clear.firstChild) {
output_to_clear.removeChild(output_to_clear.firstChild);
}
I think using jQuery's $.remove() is probably the best choice here. If you can't or don't want to use jQuery, The Mozilla docs for Node provides a function to remove all child nodes.
Element.prototype.removeAll = function () {
while (this.firstChild) { this.removeChild(this.firstChild); }
return this;
};
Which you would use like:
output_to_clear.removeAll();
For a one-off given the example provided:
while (output_to_clear.firstChild) { output_to_clear.removeChild(output_to_clear.firstChild); }

Categories

Resources