REACT.js on select disable radio button and check second option - forms

I have been changing a form based on REACT and this is something I am a newb with (been using it already for 4 months but just segments of it, sometimes actual progress with the programming is based on pure luck and every time on advices of good people found here).
Currently I have a task of re-developing a form of this look:
What I need to achieve is Calibration radios' behavior based on Type's selection: if argument calibration is set to 0 (zero) then disable option 'Accredited' and check second option automatically.
Edited: 19 Oct 2017
This creates the drop down, and the DD works great:
createSuggestInput(name) {
const { id, value, labels } = this.props;
const _t = this.props.intl.formatMessage;
var options = [
{ value: 'one', label: 'One', calibration: '0' },
{ value: 'two', label: 'Two ', calibration: '1' },
{ value: 'three', label: 'Three', calibration: '0' },
{ value: 'four', label: 'Four', calibration: '1' },
];
return <Select.Creatable
name = {`${id}_${name}`}
value = {this.state.brandSelect}
placeholder = {_t(translations.txtSuggest)}
options = {options}
onChange = {this._onChange.bind(this)}
label = {labels[name]}
key = {`${id}_${name}`}
promptTextCreator = { (label) => _t(translations.txtCreate) + ' ' + label + _t(translations.txtCreateEnter) }
/>;
}
When selected option's calibration value is ZERO, I need to update set of Calibration radio buttons, by disabling the option "Accredited" and at the same time checking the second option, "Not Accredited".
createRadioCalibration(name) {
const { id, value, labels } = this.props;
const _t = this.props.intl.formatMessage;
const ACCREDITATION_TYPES = [
[CALIBRATION_ACCREDITED, _t(messages.calibrationAccredited)],
[CALIBRATION_NOT_ACCREDITED, _t(messages.calibrationNotAccredited)]
];
return <FormChoiceGroup
type = "radio"
values = {ACCREDITATION_TYPES.map(mapValueArray)}
key = {`${id}_${name}`}
name = {`${id}_${name}`}
value = {value[name]}
handleChange = {this.handleFieldChangeFn(name)}
/>;
}
These two are rendered as follows:
render () {
const FIELDS = {
[CALIBRATION]: this.createRadioCalibration(CALIBRATION),
[TYPE]: this.createSuggestInput(TYPE),
};
return (
<div className="repair-form-device repair-form-device-field-row">
<div className="repair-form-device-id">
{id + 1}
</div>
<div className="clearfix repair-form-device-content">
<div className="">
{ FIELDS[TYPE] }
</div>
<div className="">
<label>{_t(messages.repair)}</label>
{ FIELDS[CALIBRATION] }
</div>
.....
And lastly the _onChange function:
_onChange(tool) {
const { id } = this.props;
this.setState({
brandSelect: tool
});
}
As I stated previously, I am stuck with the main task, which is manipulating the Calibration radio buttons.
I believe I can update its status inside the _onChange function, but everything I tested so far lead me nowhere.
Your patience is much appreciated!

Related

How to preselect checkbox in showQuickPick in vscode

I am using quickpick to display list of items and allowing user to do multiselect. I am using quickpick like this.
context.subscriptions.push(vscode.commands.registerCommand('command', async () => {
const list = await vscode.window.showQuickPick(filedsList, { ignoreFocusOut: true, canPickMany: true});
}));
I trying to make like if user previously selected some items in the quick pick and next time use opened this quick pick I want to preselect the previously selected values.
Is it feasible to do it in vscode extension development.
There are two options. In both cases you'll have to make QuickPickItems out of your AccurevOperations.cpkFieldsList as you cannot just pass strings as the first argument and use the pre-selection capability. It isn't difficult to do this, just loop through that AccurevOperations.cpkFieldsList array and create objects with the QuickPickItem properties you want, like:
const arr = ["1", "2", "3"];
// const quickPickItems = arr.map(item => ( { label: item, picked: true } ) ); // but this would select them all
const quickPickItems = arr.map(item => {
if (Number(item) % 2 != 0) return { label: item, picked: true };
else return { label: item }
});
So you would use your logic to set the items you want pre-selected to have the picked:true object property. Then
const options = { canPickMany: true };
const qp = vscode.window.showQuickPick(quickPickItems, options);
should show a QuickPick with your selected items.
The other option is to use the createQuickPick method instead, because with that you can use its selectedItems property. So starting with your array:
const arr = ["1", "2", "3"];
const quickPickItems = arr.map(item => ( { label: item } ) ); // and whatever other properties each item needs, perhaps nothing other than label
const qp = vscode.window.createQuickPick();
qp.canSelectMany = true;
qp.items = quickPickItems;
qp.selectedItems = [quickPickItems[0], quickPickItems[2]]; // your logic here
qp.show();
You will have to create an array of objects to assign to the selectedItems property. Perhaps by filtering the quickPickItems array (from above) for the labels you want pre-selected:
qp.selectedItems = quickPickItems.filter(item => {
return item.label === "1" || item.label === "3";
});
the object vscode::QuickPickItem has a property
picked
Optional flag indicating if this item is picked initially.

syncfusion ej chart redraw [n] undefined

I am using ASP MVC and I have a ej chart built in script, and I need to refresh its content:
my chart is built like this:
var modelSummaryList = getMySummaryModel();
var summaryChartDataManager = ej.DataManager(($scope.FirstLoad && IsCurrentUserDpiUser()) ? null : modelSummaryList);
jQuery("#MySummaryChart").ejChart({
range: { min: summaryChartDataManager == null ? -1 : summaryChartDataManager.ChartMin, max: summaryChartDataManager == null ? 1 : summaryChartDataManager.ChartMax },
series: [{
name: "MTM",
tooltip: {
visible: true,
format: "#point.x#: #point.y# #series.name#"
},
dataSource: summaryChartDataManager,
xName: "CtpyShort",
yName: "MTM"
}, {
name: "Threshold",
tooltip: {
visible: true,
format: "#point.x#: #point.y# #series.name#"
},
dataSource: summaryChartDataManager,
xName: "CtpyShort",
yName: "Threshold"
}, {
name: "My Held/(Posted)",
tooltip: {
visible: true,
format: "#point.x#: #point.y# #series.name#"
},
dataSource: summaryChartDataManager,
xName: "CtpyShort",
yName: "Held"
}],
type: 'column',
});
which is working good, but upon filter and change of data, I need to redraw the chart so I did this:
$scope.RefreshChart = function (data) {
var chart = $("#MySummaryChart").ejChart("instance");
chart.model.range.min = data.MyTradeSummaryVM.ChartMin;
chart.model.range.max = data.MyTradeSummaryVM.ChartMax;
for (var s = 0; s <= chart.model.series.length - 1; s++) {
var pts = IsCurrentUserDpiUser() ? $.grep(data.MyTradeSummaryVM, function (item) {
return item.ClientID == localStorage.getItem("MyPosting_client_sticky");
}) : data.MyTradeSummaryVM;
chart.model.series[s].points = [];
for (var p = 0; p <= pts.length - 1; p++) {
var newPt = new Object();
newPt.x = pts[p].CtpyShort;
if (chart.model.series[s].name == "MTM")
newPt.y = pts[p].MTM;
else if (chart.model.series[s].name == "Threshold")
newPt.y = pts[p].Threshold;
else if (chart.model.series[s].name == "My Held/(Posted)")
newPt.y = pts[p].Held;
newPt.visible = true;
chart.model.series[s].points.push(newPt);
}
}
chart.redraw();
};
which throws the error TypeError: n[0] is undefined on the chart.redraw() line, and I am stumped. Please note that the RefreshChart() works if I build the chart via cshtml and not javascript like this:
#(Html.EJ().Chart("MySummaryChart")
.PrimaryXAxis(pr => pr.Title(tl => tl.Text("")))
.PrimaryYAxis(pr => pr.Range(ra => ra.Max(Model.ChartMax).Min(Model.ChartMin)).Title(tl => tl.Text("")))
.CommonSeriesOptions(cr => cr.Type(SeriesType.Column).EnableAnimation(true).Marker(mr => mr.DataLabel(dt => dt.Visible(true).EnableContrastColor(true)))
.Tooltip(tt => tt.Visible(true).Format("#point.x# : #point.y# #series.name# ")))
.Series(sr =>
{
.
.
.
})
.Load("loadTheme")
.IsResponsive(true)
.Size(sz => sz.Height("400"))
.Legend(lg => { lg.Visible(true).Position(LegendPosition.Bottom); }))
but I am opting to use JS coz I need to handle null and firstload(meaning no data should appear on the chart upon first load, and unless user picks a client(filter), no data should be loaded. Which I cant seem to make it work if via html, I couldn't erase the chart xaxisregions label along with other data, the only things erased are the main Y axis points but not labels.
We have analyzed the reported scenario. We would like to you know that, when the data for chart is bind using dataSource, then while refreshing the chart with new data, you need to bind the data to series.dataSource property not to series.points, so that only chart will refresh properly. We have prepared a sample with respect the above scenario. Find the code snippet to achieve this requirement.
<input type="button" id="refreshChart" onclick="refresh()" value="Refresh Chart" />
function refresh(sender) {
var chart = $("#MySummaryChart").ejChart("instance");
for (var s = 0; s <= chart.model.series.length - 1; s++) {
//Obtained random data,
var pts = GetData().data;
var newPt = [];
for (var p = 0; p <= pts.length - 1; p++) {
if (chart.model.series[s].name == "MTM")
newPt.push({ "CtpyShort": pts[p].CtpyShort, "MTM": pts[p].MTM });
else if (chart.model.series[s].name == "Threshold")
newPt.push({ "CtpyShort": pts[p].CtpyShort, "Threshold": pts[p].Threshold });
else if (chart.model.series[s].name == "My Held/(Posted)")
newPt.push({ "CtpyShort": pts[p].CtpyShort, "Held": pts[p].Held });
}
//Assign the updated data to dataSource property
chart.model.series[s].dataSource = newPt;
}
chart.redraw();
}
In the above code in a button click event, we have refreshed the chart data. Here you need to assign the x value to CtpyShort and y values of three series to MTM, Threshold and Held, since we have mapped these properties while rendering the chart initially.
Screenshot before updating data:
Screenshot after updating data:
Sample for reference can be find from below link.
Sample Link
If you face still any concern, kindly revert us by modifying the above sample with respect to your scenario or provide your sample with replication steps which will helpful in further analysis and provide you the solution sooner.
Thanks,
Dharani.

Knockout.js - Reload a dropdown with new options using the value of another drop down

I've seen similar things, where people have wanted to do this in ASP .NET, generic JavaScript, PHP, etc., but now here we have KnockOut that throws a wrench in things, since its fields are already rendered dynamically. Now here I go wanting to rewrite a dropdown when another is changed... dynamic loading on top of dynamic loading, all in old-fashioned cascading style....
I have a dropdown, "ourTypes", I've called it, that when changed, should re-write the options of the "slots" dropdown to its left. I have a .subscribe() function that creates new options based on a limit I get from the "ourTypes" value. All well and good, but how do we make the dropdown actually reflect those new values?
HTML:
<select data-bind="options: $root.slots, optionsValue: 'Value', optionsText: 'Text', value: $data.SlotPosition"></select>
<select data-bind="options: $root.ourTypes, optionsValue: 'ID', optionsText: 'Name', value: $data.OurTypeId"></select>
JavaScript:
var slots = [
{ Text: "1", Value: "1" },
{ Text: "2", Value: "2" },
{ Text: "3", Value: "3" }
];
var ourTypes = [
{ ID:"1", Name:"None", Limit:0 },
{ ID:"2", Name:"Fruits", Limit:5 },
{ ID:"3", Name:"Vegetables", Limit:5 },
{ ID:"4", Name:"Meats", Limit:2 }
];
var dataList = [
{ SlotPosition: "1", OurTypeId: 4 },
{ SlotPosition: "2", OurTypeId: 2 },
{ SlotPosition: "3", OurTypeId: 3 }
];
var myViewModel = new MyViewModel(dataList);
ko.applyBindings(myViewModel);
function MyViewModel(dataList) {
var self = this;
self.slots = slots;
self.ourTypes = ourTypes;
self.OurTypeId = ko.observable(dataList.OurTypeId);
self.SlotPosition = ko.observable(dataList.SlotPosition);
self.OurTypeId.subscribe(function() {
if (!ko.isObservable(self.SlotPosition))
self.SlotPosition = ko.observable("1");
// Get our new limit based on value
var limit = ko.utils.arrayFirst(ourTypes, function(type) {
return type.ID == self.OurTypeId();
}).Limit;
// Build options here
self.slots.length = 0;
self.slots.push({Text:"",Value:""});
for (var i=1; i < limit+1; i++) {
self.slots.push({Text:i, Value:i});
}
// What else do I do here to make the dropdown refresh
// with the new values?
});
}
Fiddle: http://jsfiddle.net/navyjax2/Lspwc4n4/
Well just made small changes in you code
View Model:
self.slots = ko.observableArray(slots); //should make it observable
self.ourTypes = ko.observableArray(ourTypes);
self.OurTypeId = ko.observable(dataList[0].OurTypeId); // initial value setting
self.SlotPosition = ko.observable(dataList.SlotPosition);
//Inside subscribe
self.slots([]); // clearing before filling new values
Working fiddle here

Dojo domConstruct - Inserting rows into a table

I'm working on an application that will allow people to select which data fields they would like a form to have. I had it working but when I tried to move the form fields into a table for a bit of visual structure I'm running into a problem.
// Now print the form to a new div
array.forEach(selectedFields, function(item, i) {
var l = domConstruct.create("label", {
innerHTML: item + ': ',
class: "dataFieldLabel",
for: item
});
var r = new TextBox({
class: "dataField",
name: item,
label: item,
title: item
});
var a = domConstruct.toDom("<tr><td>" + l + r + "</td></tr>");
domConstruct.place(a, "displayDataForm");
When I run the code I can select the fields I want but instead of textboxes being drawn on the screen text like:
[object HTMLLabelElement][Widget dijit.form.TextBox, dijit_form_TextBox_0]
[object HTMLLabelElement][Widget dijit.form.TextBox, dijit_form_TextBox_1]
Is printed to the screen instead. I think this is because I am passing domConstruct.place a mixture of text and objects. Any ideas about how to work around this? Thanks!
Try this :
require(["dojo/_base/array", "dojo/dom-construct", "dijit/form/TextBox", "dojo/domReady!"], function(array, domConstruct, TextBox){
var selectedFields = ["Foo", "Bar", "Baz"];
array.forEach(selectedFields, function(item, i) {
var tr = domConstruct.create("tr", {}, "displayDataForm"),
td = domConstruct.create("td", {}, tr),
l = domConstruct.create("label", {
innerHTML: item + ': ',
'class': 'dataFieldLabel',
'for': item
}, td, 'first'),
r = new TextBox({
'class': 'dataField',
name: item,
title: item
}).placeAt(td, 'last');
});
});
This assumes you have this in your html :
<table id="displayDataForm"></table>
Don't forget to quote "class" and "for" as these are part of javascript's grammar.
The domConstruct functions will not work with widgets. You can create the html and then query for the input node and create the test box.
var root = dom.byId("displayDataForm");
domConstruct.place(root,
lang.replace(
'<tr><td><label class="dataFieldLabel" for="{0}>{0}:</label><input class="inputNode"></input></td></tr>',
[item])
);
query('.inputNode', root).forEach(function(node){
var r = new TextBox({
'class': "dataField",
name: item,
label: item,
title: item
});
});
Craig thank you for all your help, you were right except that in the call to domConstruct.place the first argument is the node to append and the second argument is the refNode to append to. Thank you.
// Now print the form to a new div
array.forEach(selectedFields, function(item, i) {
var root = dom.byId("displayDataForm");
domConstruct.place(lang.replace(
'<tr><td><label class="dataFieldLabel" for="{0}">{0}: </label><input class="dataField"></input></td></tr>',
[item]), root
);
query('.dataField', root).forEach(function(node) {
var r = new TextBox({
'class': "dataField",
name: item,
label: item,
title: item
});
});
});

Handle selected event in autocomplete textbox using bootstrap Typeahead?

I want to run JavaScript function just after user select a value using autocomplete textbox bootstrap Typeahead.
I'm searching for something like selected event.
$('.typeahead').on('typeahead:selected', function(evt, item) {
// do what you want with the item here
})
$('.typeahead').typeahead({
updater: function(item) {
// do what you want with the item here
return item;
}
})
For an explanation of the way typeahead works for what you want to do here, taking the following code example:
HTML input field:
<input type="text" id="my-input-field" value="" />
JavaScript code block:
$('#my-input-field').typeahead({
source: function (query, process) {
return $.get('json-page.json', { query: query }, function (data) {
return process(data.options);
});
},
updater: function(item) {
myOwnFunction(item);
var $fld = $('#my-input-field');
return item;
}
})
Explanation:
Your input field is set as a typeahead field with the first line: $('#my-input-field').typeahead(
When text is entered, it fires the source: option to fetch the JSON list and display it to the user.
If a user clicks an item (or selects it with the cursor keys and enter), it then runs the updater: option. Note that it hasn't yet updated the text field with the selected value.
You can grab the selected item using the item variable and do what you want with it, e.g. myOwnFunction(item).
I've included an example of creating a reference to the input field itself $fld, in case you want to do something with it. Note that you can't reference the field using $(this).
You must then include the line return item; within the updater: option so the input field is actually updated with the item variable.
first time i've posted an answer on here (plenty of times I've found an answer here though), so here's my contribution, hope it helps. You should be able to detect a change - try this:
function bob(result) {
alert('hi bob, you typed: '+ result);
}
$('#myTypeAhead').change(function(){
var result = $(this).val()
//call your function here
bob(result);
});
According to their documentation, the proper way of handling selected event is by using this event handler:
$('#selector').on('typeahead:select', function(evt, item) {
console.log(evt)
console.log(item)
// Your Code Here
})
What worked for me is below:
$('#someinput').typeahead({
source: ['test1', 'test2'],
afterSelect: function (item) {
// do what is needed with item
//and then, for example ,focus on some other control
$("#someelementID").focus();
}
});
I created an extension that includes that feature.
https://github.com/tcrosen/twitter-bootstrap-typeahead
source: function (query, process) {
return $.get(
url,
{ query: query },
function (data) {
limit: 10,
data = $.parseJSON(data);
return process(data);
}
);
},
afterSelect: function(item) {
$("#divId").val(item.id);
$("#divId").val(item.name);
}
Fully working example with some tricks. Assuming you are searching for trademarks and you want to get the selected trademark Id.
In your view MVC,
#Html.TextBoxFor(model => model.TrademarkName, new { id = "txtTrademarkName", #class = "form-control",
autocomplete = "off", dataprovide = "typeahead" })
#Html.HiddenFor(model => model.TrademarkId, new { id = "hdnTrademarkId" })
Html
<input type="text" id="txtTrademarkName" autocomplete="off" dataprovide="typeahead" class="form-control" value="" maxlength="100" />
<input type="hidden" id="hdnTrademarkId" />
In your JQuery,
$(document).ready(function () {
var trademarksHashMap = {};
var lastTrademarkNameChosen = "";
$("#txtTrademarkName").typeahead({
source: function (queryValue, process) {
// Although you receive queryValue,
// but the value is not accurate in case of cutting (Ctrl + X) the text from the text box.
// So, get the value from the input itself.
queryValue = $("#txtTrademarkName").val();
queryValue = queryValue.trim();// Trim to ignore spaces.
// If no text is entered, set the hidden value of TrademarkId to null and return.
if (queryValue.length === 0) {
$("#hdnTrademarkId").val(null);
return 0;
}
// If the entered text is the last chosen text, no need to search again.
if (lastTrademarkNameChosen === queryValue) {
return 0;
}
// Set the trademarkId to null as the entered text, doesn't match anything.
$("#hdnTrademarkId").val(null);
var url = "/areaname/controllername/SearchTrademarks";
var params = { trademarkName: queryValue };
// Your get method should return a limited set (for example: 10 records) that starts with {{queryValue}}.
// Return a list (of length 10) of object {id, text}.
return $.get(url, params, function (data) {
// Keeps the current displayed items in popup.
var trademarks = [];
// Loop through and push to the array.
$.each(data, function (i, item) {
var itemToDisplay = item.text;
trademarksHashMap[itemToDisplay] = item;
trademarks.push(itemToDisplay);
});
// Process the details and the popup will be shown with the limited set of data returned.
process(trademarks);
});
},
updater: function (itemToDisplay) {
// The user selectes a value using the mouse, now get the trademark id by the selected text.
var selectedTrademarkId = parseInt(trademarksHashMap[itemToDisplay].value);
$("#hdnTrademarkId").val(selectedTrademarkId);
// Save the last chosen text to prevent searching if the text not changed.
lastTrademarkNameChosen = itemToDisplay;
// return the text to be displayed inside the textbox.
return itemToDisplay;
}
});
});