I use Axios to GET data from my server. Basically, what I want to achieve is use the response from the GET request and get the data to set the checkbox to true or false depending on the response.
But the problem is, it does not set the checkbox to true or false. But rather, the value of this.checked will always be "".
Here is my code:
<template>
<input type="checkbox" value="Yes" v-model="checked">Yes</label>
</template>
export default {
data () {
return {
checked: ''
}
}
...
...
created () {
...
...
if ((response.data.categoryTypeId) === noSubCat) {
// checkbox is not checked
this.checked === false
} else {
// checkbox is checked
this.checked === true
}
}
}
You should assigne the value, instead you're doing a comparisation with ===
created () {
...
...
if ((response.data.categoryTypeId) === noSubCat) {
// checkbox is not checked
// this.checked === false // this is a comparison
// I guess is assign what you want.
this.checked = false
} else {
// checkbox is checked
this.checked = true
}
}
}
And you can simplify the code above to something like this:
this.checkbox = (response.data.categoryTypeId) === noSubCat ? false : true;
Related
I've got two checkboxes and I need to have only one of them true at the time.
So if checkbox1 is true then checkbox2 should be false.
My current code works only when I play around with first checkbox but the second one doesn't behave correctly.
Here are my checkboxes:
<Checkbox
checked={checkbox1}
onChange={onChange}
/>
<Checkbox
checked={checkbox2}
onChange={onChange}
/>
My CheckBox component:
<input
type="checkbox"
className="filled-in"
checked={this.state.checked}
data-cy={this.props.cyCheckbox}
/>
And my parent component where I am trying to manipulate state to set CheckBox checked true or false:
<Access
checkbox1={this.state.input.checkbox1}
checkbox2={this.state.input.checkbox2}
onChange={this.updateInput}
/>;
state = {
input:{
checkbox1: false,
checkbox2: false,
}
}
updateInput = (key, value) => {
let { input } = this.state;
input[key] = value;
this.setState({ input });
window.input = input;
//this is where I try to set another Checkbox false if first one is true.
if (input.checkbox1) {
input.checkbox2= false;
} else if (input.checkbox2) {
input.checkbox1= false;
} else {
input.checkbox2= true;
input.checkbox1= true;
}
}
I can't be sure because your examples are incomplete, but I think your issue is that your checkbox code can never reach the else if clause unless the first checkbox is already unchecked. Make your conditionals based on key and value and you'll be fine. Something like:
if (key === 'checkbox1' && value) {
input.checkbox1 = true;
input.checkbox2 = false;
} else if (key === 'checkbox2' && value) {
input.checkbox1 = false;
input.checkbox2 = true;
}
I have a button which basically imports some data. This imported data needs to be compared with the data inside already loaded ag-grid and if there is a match, set the cehckbox of that particlar row node to true.
This is the button which checks for the condition:
enableCheck() {
alert('works');
if (this.DataService.isNotBlank(this.rowDataImport)) {
for (let i = 0; i < this.rowDataImport.length; i++) {
if (this.DataService.isNotBlank(this.rowData)) {
for (let j = 0; j < this.rowData.length; j++) {
if (this.DataService.isNotBlank(this.rowData[j].calDate)) {
for (const calDates of this.rowData[j].calDate) {
if (
this.rowDataImport[i].isin === calDates.isin ||
this.rowDataImport[i].portfolioName === calDates.portfolioName ||
this.rowDataImport[i].valuationDate === calDates.valuationDate
)
{
// alert('true')
this.checkValue = true;
} else {
this.checkValue = false;
}
}
}
}
}
}
}
}
The this.checkValue is a flag which will be true if match is found.
public gridColumnDefs = [
{
headerName: 'Portfolio Name',
field: 'portfolioName',
cellRenderer: 'agGroupCellRenderer',
headerCheckboxSelection: true,
headerCheckboxSelectionFilteredOnly: true,
checkboxSelection: true,
pinned: 'left',
filter: true,
cellRendererParams:(params) => {
console.log(params);
if (this.checkValue) {
params.node.selected = true;
}
}
},
]
here I used cellRendererParams. But this will only for on load I guess. What to do if I want to update the ag-grid row from a value outside i.e. from import check as given above?
First of all, you should add id for each row in defaultColDef
this.defaultColDef = {
getRowNodeId: data => data.id,
};
Then you can find this id and set the checkbox to true.
Also, you can find separate field by name.
It is really easy, you should use the next combination
selectRow() {
this.gridApi.forEachNode(node => {
if (node.id == 1 || node.id == 2 || node.data.country == 'Australia') {
node.setSelected(true);
}
});
}
Working example:
https://plnkr.co/edit/ijgg6bXVleOAmNL8
In this example when we click on the button - we set the checkbox to true for two rows with id 1 and 2 and for each field that has country 'Australia'
And in your case, you are using incorrect configuration.
You should you cellRenderer
cellRenderer: params => {
if(params.value === 'Ireland') {
params.node.setSelected(true)
}
return params.value
},
One more example: https://plnkr.co/edit/PcBklnJVT2NsNbm6?preview
I manpulated a bit and did the below which worked like a charm.
this.gridApi.forEachNode(node => {
if (node.data.isin === this.rowDataImport[i].isin &&
node.data.portfolioName === this.rowDataImport[i].portfolioName &&
node.data.valuationDate === this.rowDataImport[i].valuationDate
) {
node.setSelected(true);
}
I am trying to implement a checkout form in React. The form has 4 fields in all: Name, CC Number, CC expiration and CVV. I am using a library that validates each field on unfocus. The validation is triggered by the validationCallback method which takes 3 arguments: field, status, and message. I'd like to key off of the status for each input and only allow submit once each status === true. Here is my code.
constructor(props) {
super(props);
this.state = {
nameOnCard: '',
errorMessage: '',
showLoaderForPayment: '',
collectJs: null,
token: null,
isPaymentRequestCalled: false,
showErrorModal: false,
paymentErrorText: '',
disabled: true,
};
}
I have a disabled property in my state which I'm initially setting to true.
validationCallback: (field, status, message) => {
if (status) {
this.setState({ errorMessage: '' });
} else {
let fieldName = '';
switch (field) {
case 'ccnumber':
fieldName = 'Credit Card';
break;
case 'ccexp':
fieldName = 'Expire Date';
break;
case 'cvv':
fieldName = 'Security Code';
break;
default:
fieldName = 'A';
}
if (message === 'Field is empty') {
this.setState({ errorMessage: `${fieldName} ${message}` });
} else {
this.setState({ errorMessage: `${message}` });
}
}
},
In the above method, I'd like to set disabled to false if each of the field's status===true... Below is the button which I'm setting to be the value of this.state.disabled.
<button
className="continueBtn disabled"
disabled={this.state.disabled}
onClick={this.handleCardSubmit}
>
<span className="fa fa-lock" />
Pay $
{selectedPayment.amount}
</button>
I hope this is enough of the code to help with the issue. I can provide more of the file if need be.
From what i understand, you want to set the button to NOT DISABLED if all the fields are filled properly, i.e. all status are true.
What you can do is maintain a boolean array for each field and update the status in that array, i.e. initialize an array of length = no. of fields (in your case 3) and set all values as false. False depicts that the field hasn't been validated.
this.state = {
statusArray = [false, false, false] // For as many fields
}
Then in validationCallback, set the index as true or false for that field i.e. if the 2nd field status is returned true by your validation library, set statusArray as [false, true, false].
The form will only be validated if all 3 of the values become true. So you can iterate over the array and check if array has all 3 values as true. or you can use the logical AND operator which returns true only if all values are true(the approach which i use below).
For the button,
<button disabled={this.checkDisable()}>
checkDisable = () => {
let temp = this.state.statusArray;
let answer = true;
for(int i=0;i<temp.length;i++)
answer = answer && temp[i];
return answer; // Only returns true if all 3 values are true
}
I hope you get it now.
You need to check 2 things, has the form been touched and are there any errors. I don't know what library you are using but most likely it has a property touched in it, if not add an onFocus to each input field and a touched property in your state. You don't really need a disabled property in your state since its a computed value. Just check on every render if the form has been touched and if there are any errors.
state = {
...,
touched: false,
...
}
handleFocus = () => this.setState({touched: true})
render(){
const disabled = !!(this.state.touched && this.state.errorCode)
return(
...
<input onFocus={this.handleFocus} ... />
...
<button disabled={disabled}
)
}
EDIT:
state = {
...
validInputs: []
}
validationCallback: (field, status, message) => {
if (status) {
this.setState((state) => ({ errorMessage: '', validInputs: [... new Set([...state.validInputs, field])] }));
} else {
...
render(){
const disabled = this.state.length < inputs.length // the number of the input fields
return(
...
<button disabled={disabled} >
...
)
My UI-grid is not reflecting changing based on the checkbox.
Checkbox I have is --> mainCtrl.check700 (either true or false)
UI Grid does not refresh based on the checkbox change. How do i make the UI grid to change isrowselectable based on checkbox
mainCtrl.mainGrid.isRowSelectable = function (row) {
if (mainCtrl.check700){
if (row.entity.detailStatus === '700') {
return true;
} else {
return false;
}
}else{
if (row.entity.detailStatus === '100' || row.entity.detailStatus === '200' ) {
return true;
} else {
return false;
}
}
};
You need to assign it to $scope.gridOptions
So in your case I suppose using mainCtrl.gridOptions.isRowSelectable = ... instead of mainCtrl.mainGrid.isRowSelectable should solve the problem.
i am using kendo ui tree view with check box
i want the check box's id when it is getting unchecked
this is kendo ui mine code
// var homogeneous contains data
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: false,
template:"# if(!item.hasChildren){# <input type='hidden' id='#=item.id#' parent_id='#=item.parent_id#' d_text='#=item.value#'/> <input type='checkbox' id_a='#= item.id #' name='c_#= item.id #' value='true' />#}else{# <div id='#=item.id#' style='display:none;' parent_id='#=item.parent_id#' d_text='#=item.value#'/> #}#",
},
dataSource: homogeneous,
dataBound: ondata,
dataTextField: "value"
});
function ondata() {
//alert("databound");
}
// function that gathers IDs of checked nodes
function checkedNodeIds(nodes, checkedNodes) {
//console.log(nodes);
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].id);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}
// show checked node IDs on datasource change
$("#treeview").data("kendoTreeView").dataSource.bind("change", function() {
var checkedNodes = [],
treeView = $("#treeview").data("kendoTreeView"),
message;
checkedNodeIds(treeView.dataSource.view(), checkedNodes);
if (checkedNodes.length > 0) {
message = "IDs of checked nodes: " + checkedNodes.join(",");
} else {
message = "No nodes checked.";
}
$("#result").html(message);
});
in this code i am not getting checkbox's id when it is unchecked so i have tried this
jquery code
$('input[type=checkbox]').click(function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('not checked');
}
});
this code is only working in js fiddle but not in my case http://jsfiddle.net/NPUeL/
if i use this code then i can get the number of count but i dont know how to use it
var treeview = $("[data-role=treeview]").data("kendoTreeView");
treeview.dataSource.bind("change", function (e) {
if (e.field == "checked") {
console.log("Recorded Selected: " + $("[data-role=treeview] :checked").length);
}
});
what changed i need to do in data source so i can get id
thanks in adavance
If you want to get the id you might do:
$('input[type=checkbox]').click(function (e) {
var li = $(e.target).closest("li");
var id = $("input:hidden", li).attr("id");
var node = treeView.dataSource.get(id);
if (node.checked) {
console.log('checked');
} else {
console.log('not checked');
}
});
What I do in the event handler is:
find the closest li element that is the node of the tree that has been clicked.
the id is in an HTML input element that is hidden (this is the way that I understood that you have stored it).
Get item from dataSource using dataSource.get method.
See your code modified and running here
i made the small change and its working now
function ondata() {
$('input[type=checkbox]').click(function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('not checked');
}
});
}