I am trying to set an initial value for a select, but not showing in the view.
My jsx:
var SelectOKNO = React.createClass({
render() {
return (
<div>
<select className="selectpicker" value={this.props.value}
onChange={this.props.onChange.bind(this)}>
<option value=""></option>
<option value="OK">OK</option>
<option value="NO">NO</option>
</select>
</div>
)
}
});
var Detalle = React.createClass({
getInitialState: function() {
return({
ID:'',
UREFValue: '',
URCorrectoValue: '',
ConcordanciaValue: '',
PruebasValue: '',
EmergenciasValue: '',
ComentarioValue: '',
EstadoValue:'',
rec_fecha_aprobacion:'',
rec_aplica_control: '',
rec_auditor: ''
});
},
handleChange: function (key) {
return function (e) {
var state = {};
state[key] = e.target.value;
this.setState(state);
}.bind(this);
},
componentDidMount: function() {
$.ajax({
url: 'url',
data: { //Passing data
id: $("#hdnID").val()
},
dataType: 'json',
cache: false,
success: function(data) {
this.setState({
ID:data.rec_id,
UREFValue:data.rec_inconveniente_usuario_ref,
URCorrectoValue:data.rec_usuario_ref_correcto,
ConcordanciaValue:data.rec_concordancia_doc,
PruebasValue:data.rec_pruebas,
EmergenciasValue:data.rec_emergencia,
ComentarioValue:data.rec_comentario,
EstadoValue: data.rec_estado,
rec_fecha_aprobacion:data.rec_fecha_aprobacion,
rec_aplica_control: data.rec_aplica_control,
rec_auditor: data.rec_auditor
});
}.bind(this),
error: function(xhr, status, err) {
}.bind(this)
});
},
render() {
return (
<form onSubmit={this.handleSubmit}>
<br/>
<table className="table borderless">
<tr className ="row">
<td>Usuario Referente:
<SelectOKNO value={this.state.UREFValue} onChange={this.handleChange('UREFValue').bind(this)}/>
</td>
<td>UR Correcto:
<textarea rows="3" className="form-control noresize" value={this.state.URCorrectoValue} onChange={this.handleChange('URCorrectoValue')} />
</td>
</tr>
<tr className ="row">
<td>Concordancia:
<SelectOKNO value={this.state.ConcordanciaValue} onChange={this.handleChange('ConcordanciaValue')}/>
</td>
<td>Pruebas:
<SelectOKNO value={this.state.PruebasValue} onChange={this.handleChange('PruebasValue')}/>
</td>
</tr>
<tr className ="row">
<td>Emergencias:
<SelectOKNO value={this.state.EmergenciasValue} onChange={this.handleChange('EmergenciasValue').bind(this)}/>
</td>
<td>Comentario:
<textarea rows="3" className="form-control noresize" value={this.state.ComentarioValue} onChange={this.handleChange('ComentarioValue')} />
</td>
</tr>
<tr className ="row">
<td>
<select className="selectpicker" value={this.state.EstadoValue}
onChange={this.handleChange('EstadoValue')}>
<option value="Abierto">Abierto</option>
<option value="EN_PROCESO">En Proceso</option>
<option value="CON_INCONVENIENTES">Con Inconvenientes</option>
<option value="COMPLETO">Completo</option>
</select>
</td>
<td>
<button type="submit" className="btn btn-default">Guardar</button>
</td>
</tr>
</table>
</form>
)
}
});
When page loads, all the select shows value like ''.
But in debug view of chrome I can see the value
How to set selected on options elements. Also, check what that means in React.
Finally, some nice libraries:
react-select and
react-bootstrap
Related
I am struggling to make it work to pass element id to Jquery from html foreach loop. I have a table and I am getting the details from database. so in each loop we are getting new data for new users. I am using bootstrap switch as seen below :
<form method="post" id="toggleForm">
<fieldset>
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="customSwitch1" name='machine_state' status="{{$detail['status']}}">
<input type="hidden" id="id" value="{{$detail['id']}}" >
<label class="custom-control-label" id="statusText" for="customSwitch1"> </label>
<llittle id ="littleupdate"></llittle>
</div>
</div>
</fieldset>
</form>
In the Jquery part we have three functions as shown below:
function putStatus() {
var id = $("#id").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: "/admin/check-status",
data: {id : id},
success: function (result) {
if (result == "true") {
$('#customSwitch1').prop('checked', true);
statusText(1);
} else {
$('#customSwitch1').prop('checked', false);
statusText(0);
}
}, error:function (){
}
});
}
function statusText(status_val) {
if (status_val == 1) {
var status_str = "Active";
} else {
var status_str = "Inactive";
}
document.getElementById("statusText").innerText = status_str;
}
function onToggle() {
$('#toggleForm :checkbox').change(function () {
if (this.checked) {
//alert('checked');
updateStatus(1);
// statusText(1);
} else {
//alert('NOT checked');
updateStatus(0);
// statusText(0);
}
});
}
function updateStatus(status_val) {
var id = $('#id').val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "/admin/set-status",
data: {status: status_val, id:id},
success: function (result) {
if(result =="true") {
if(status_val == 1) {
$('#customSwitch').prop('checked', true);
// $("#updatedAt").fadeIn(0).html("<font color='green' font size='2px'> - Updated.. User Activated!</font>").fadeOut(1500);
// $( '#littleupdate').fadeIn(0).html("<font color='green' font size='1px'> Updated.. </font>").fadeOut(1500);
statusText(1);
} else if(status_val == 0){
$('#customSwitch').prop('checked', false);
// $("#updatedAt").fadeIn(0).html("<font color='green' font size='2px'> - Updated.. User Deactivated!</font>").fadeOut(1500);
// $( '#littleupdate').fadeIn(0).html("<font color='green' font size='1px'> Updated.. </font>").fadeOut(1500);
statusText(0);
}
} else {
if(status_val == 1){
$('#customSwitch1').prop('checked', false);
$("#updatedAt").fadeIn(0).html("<font color='red'> - Error while updating!</font>").fadeOut(1500);
} else if(status_val == 0){
$('#customSwitch1').prop('checked', true);
$("#updatedAt").fadeIn(0).html("<font color='red'> - Error while updating!</font>").fadeOut(1500);
}
}
}, error:function (){
}
});
}
$(document).ready(function () {
//Called on page load:
putStatus();
onToggle();
statusText();
});
Html loop as a whole is looking like below:
#foreach($details as $detail)
<tr>
<td>
{{$detail['id']}}
</td>
<td>
{{$detail['name']}}
</td>
<td>
{{$detail['type']}}
</td>
<td>
{{$detail['email']}}
</td>
<td>
<img src="{{asset('/admin/images/avatars/'.$detail['image'])}}">
</td>
<td>
{{$detail['mobile']}}
</td>
<td>
<form method="post" id="toggleForm">
<fieldset>
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="customSwitch1" name='machine_state' status="{{$detail['status']}}">
<input type="hidden" id="id" value="{{$detail['id']}}" >
<label class="custom-control-label" id="statusText" for="customSwitch1"> </label>
<llittle id ="littleupdate"></llittle>
</div>
</div>
</fieldset>
</form>
</td>
I really can't figure out the mechanism of passing the function to each loop element, as it only works correctly for the first instance in the table as can be seen in image below. Your help would be highly appreciated.
Because in loop , the id attribute is the same
In loop
<form method="post" id="toggleForm_{{$detail['id']}}">
<fieldset>
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="customSwitch_{{$detail['id']}}" name='machine_state' status="{{$detail['status']}}">
<input type="hidden" class="statusForDetail" value="{{$detail['id']}}" >
<label class="custom-control-label" id="statusText_{{$detail['id']}}" for="customSwitch_{{$detail['id']}}"> </label>
<llittle id="littleupdate_{{$detail['id']}}"></llittle>
</div>
</div>
</fieldset>
</form>
function putStatus() {
$(".statusForDetail").each((index, element) => {
let id = $(element).val()
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: "/admin/check-status",
data: {id : id},
success: function (result) {
if (result == "true") {
$('#customSwitch_'+id).prop('checked', true);
statusText(1);
} else {
$('#customSwitch_'+id).prop('checked', false);
statusText(0);
}
}, error:function (){
}
});
});
}
I am using formArray to display dynamic data in table and its working as expected, but I am unable to apply the required field validation. I want to validate this table so that no null entry can be save.
In template:
<form *ngIf="userForm" [formGroup]="userForm">
<table>
<tbody formArrayName="order">
<ng-container *ngFor="let orderLine of properties; let i=index" [formGroupName]="i">
<tr>
<td class="fieldspacing">
<input class="form-control" formControlName="propertyName"
[readOnly]="orderLine.IsReadOnly" type="text">
<ng-container *ngIf="order.get('propertyName').hasError('required')">
<span class="errorMsg">Property name cannot be null</span>
</ng-container>
</td>
<td class="fieldspacing">
<select class="form-control selectwidth" formControlName="propertyType" type="text"
(change)="valueChange(i)">
<option *ngFor="let type of propertyTypes" value="{{type.Id}}">{{type.TypeName}}
</option>
</select>
</td>
<div *ngIf="orderLine.PropertyTypeId == 4">
<td class="fieldspacing">
<input type="checkbox" formControlName="readOnly" (change)="handleSelected($event,i)"><label> Has
Parent</label>
</td>
<td class="fieldspacing" *ngIf="orderLine.IsReadOnly || contentEditable">
<select class="form-control selectwidth" formControlName="parentProperty" type="text">
<option *ngFor="let parent of properties" [value]="parent.ParentHierarchyPropertyId">
{{parent.ParentHierarchyPropertyName}}
</option>
</select>
</td>
</div>
</tbody>
</table>
<button (click)="saveUserAdditionalProperties()" type="submit"
class="mt-4 btn btn-primary">Save</button>
</form>
In controller
public properties: any = [
{
"Id": "0012",
"PropertyType": null,
"PropertyTypeId": 4,
"IsReadOnly": true,
"DisplayOrder": 0,
"PropertyName": "Gender",
"ParentHierarchyPropertyId": null,
"ParentHierarchyPropertyName": null,
},
{
"Id": "1234",
"PropertyType": null,
"PropertyTypeId": 4,
"IsReadOnly": false,
"DisplayOrder": 1,
"PropertyName": "save",
"ParentHierarchyPropertyId": null,
"ParentHierarchyPropertyName": null,
},
];
loadUserProperties() {
this.userForm = this.getForm();
}
getForm(): FormGroup {
return new FormGroup({
order: new FormArray(this.properties.map(this.getFormGroupForUserProperty)),
});
}
getFormGroupForUserProperty(userProperty: any) {
let formGroup: FormGroup = new FormGroup({
propertyName: new FormControl(userProperty.PropertyName,Validators.required),
propertyType: new FormControl(userProperty.PropertyTypeId),
parentProperty: new FormControl(userProperty.ParentHierarchyPropertyId),
readOnly: new FormControl(userProperty.IsReadOnly)
});
You need to use it for formArray
formArray: FormArray;
constructor(
private _formBuilder: FormBuilder
) {}
this.formArray = this._formBuilder.array([]);
new Array(LENGTH_NUMBER).fill(1).forEach(() => {
this.formArray.push(this._formBuilder.group({
FORMCONTROLNAME_ONE: ["", Validators.required],
FORMCONTROLNAME_TWO: ["", Validators.required],
FORMCONTROLNAME_THREE: ["", Validators.required]
}))
});
HTML side
<ng-container *ngFor="let formGroup of formArray.controls;">
<div [formGroup]="formGroup">
<input formControlName="FORMCONTROLNAME_ONE">
<input formControlName="FORMCONTROLNAME_TWO">
<input formControlName="FORMCONTROLNAME_THREE">
</div>
</ng-container>
Obviously you can apply a filter on the userForm that
if(userForm.value.order.length!==0){
// submit
}else{
// not submit
}
I'm pretty new to angularjs.So,please kindly ignore if there are any errors.Here I have one dropdownlist within ng-repeat if I select the values in dropdownlist the corresponding Item code and the selected description from dropdownlist should pass to angularcontroller and I need to post it to the mvc controller
angular.module('myApp', [])
.controller('ctrl', ['$scope', '$http', '$rootScope',function ($scope, $http,$rootScope) {
$scope.values = [{
Code: 1,
Description: 'Apple'
}, {
Code: 2,
Description: 'Orange'
}, {
Code: 3,
Description: 'Mango'
}, {
COde: 4,
Description: 'Guva'
}
];
$scope.ddlrhs = '';
$scope.data = [{
Code: 1,
Description: 'Red'
}, {
Code: 2,
Description: 'Orange'
}, {
Code: 3,
Description: 'Yellow'
}, {
Code: 4,
Description: 'Green'
}
];
$scope.submit = function ()
{
$scope.list = [];
for (var i = 0; i < $scope.values.length; i++) {
var j = "";
$scope.list.push({
VALUE: $scope.values[i].Code,
Description: $scope.myForm.items[i].Description
})
}
$http({
method: "POST",
url: "/Controller/Save",
data:
$scope.list
})
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<div id="dvcollection" ng-App="myApp" ng-controller="ctrl" >
<form name="myForm" >
<table id="tblcollections">
<thead>
<tr >
<th>ItemCode</th>
<th>ItemDesc</th>
<th>DropdownDesc</th>
<th>DropdownCode</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in values">
<td><span>{{item.Code}}</span> </td>
<td>{{item.Description}}</td>
<td>
<select ng-model="myForm.items[$index]" ng-options=" element.Description for element in data ">
<option value="">Select </option>
</select>
</td>
<td><span>{{myForm.items[$index].Code}}</span></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<input type="button" value="save" ng-click="submit()"style="float:right;" >
</td>
</tr>
</tbody>
</table>
</form>
</div>
Hey May be this might be your expectation
<div ng-app="myApp" >
<div id="dvcollection" ng-controller="ctrl">
<form name="myForm">
<table id="tblcollections">
<thead>
<tr>
<th>ItemCode</th>
<th>ItemDesc</th>
<th>DropdownDesc</th>
<th>DropdownCode</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in values">
<td><span>{{item.Code}}</span> </td>
<td>{{item.Description}}</td>
<td>
<select ng-model="itemssample" ng-options=" element.Description for element in data " ng-change="pushingelement(item.Code,itemssample.Code)">
<option value="">Select </option>
</select>
</td>
<td><span>{{myForm.items[$index].Code}}</span></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<input type="button" value="save" ng-click="submit()" style="float:right;">
</td>
</tr>
</tbody>
</table>
</form>
<div> This is written to ensure that mapping is stored or not. (Not necessary)
<p ng-repeat="item in list">
Mapping of {{$index}} element {{item.ItemCode}} -> {{item.ColorCode}}
</p>
</div>
</div>
</div>
Ensure that your MVC Controller should have a model as
public class MapperClass
{
public int ItemCode { get; set; }
public int ColorCode { get; set; }
}
SCRIPT
angular.module('myApp', [])
.controller('ctrl', ['$scope', '$http', '$rootScope', function ($scope, $http, $rootScope) {
$scope.list = [];
$scope.values = [
{ Code: 1, Description: 'Apple' },
{ Code: 2, Description: 'Orange' },
{ Code: 3, Description: 'Mango' },
{ Code: 4, Description: 'Guva' }
];
$scope.ddlrhs = '';
$scope.data = [
{ Code: 1, Description: 'Red' },
{ Code: 2, Description: 'Orange' },
{ Code: 3, Description: 'Yellow' },
{ Code: 4, Description: 'Green' }
];
$scope.pushingelement = function (itemCode, colorCode) {
var temp = { "ItemCode": itemCode, "ColorCode": colorCode };
$scope.list.push(temp);
console.log($scope.list);
}
$scope.submit = function () {
$http({
method: "POST",
url: "/Controller/Save",
data:
object:$scope.list
})
}
}
]);
TRY ONCE I HOPE IT HELPS YOU
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>get selected value from dropdownlist in angularjs</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('sampleapp', [])
app.controller('samplecontrol', function ($scope) {
$scope.sample = [{
id: '1',
name: 'Red'
}, {
id: '2',
name: 'Green'
}, {
id: '3',
name: 'Orange'
}, {
id: '4',
name: 'Yellow'
}];
});
</script>
</head>
<body data-ng-app="sampleapp" data-ng-controller="samplecontrol">
<form id="form1">
Select Name:
<select data-ng-model="ddlvalue">
<option value="">--Select--</option>
<option data-ng-repeat="t in sample" value="">{{t.name}}</option>
</select>
</form>
</body>
</html>
I am trying to select all checkboxes with one single checkbox. But how to do that?
This is my HTML:
<input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
<!-- userlist -->
<!--<div id="scrollArea" ng-controller="ScrollController">-->
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>
I create an extra checkbox to selecet and unselect all checkboxes.
JS:
.controller('UsersCtrl', function($scope, $http){
$http.get('users.json').then(function(usersResponse) {
$scope.users = usersResponse.data;
});
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = true;
});
};
});
I tried this too, but none of them works for me :(
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = $scope.selectAll;
});
};
You are missed the container divs with ng-controller and ng-app and angular.module.
user.select = $scope.selectAll is the correct variant.
https://jsfiddle.net/0vb4gapj/1/
Try setting the checked boxes against each user to be checked when the top checkbox is checked:
<input type="checkbox" ng-model="selectAll"/>
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select" ng-checked="selectAll"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>
Here is a JSFiddle you can use ng-checked with a variable on it like user.checked (or use the user.select as you want)
<div ng-app="app" ng-controller="dummy">
<table>
<tr ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>
<input type="checkbox" ng-click="usersetting(user)" ng-checked="user.checked" ng-model="user.select">
</td>
<td><tt>{{user.select}}</tt>
<br/>
</td>
</tr>
</table>
<button ng-click="checkAll()">Check all</button>
</div>
JS:
var app = angular.module("app", []);
app.controller('dummy', function($scope) {
$scope.users = [{
id: 1,
name: "Hello",
select: 1
}, {
id: 2,
name: "World",
select: 1
}, ];
$scope.checkAll = function() {
angular.forEach($scope.users, function(user) {
user.checked = 1;
});
}
});
Simple use the following code
HTML
<input type="checkbox" ng-model="checkboxes.checked" data-ng-click="checkAll()" class="select-all" value="" />
JS
$scope.checkAll = function() {
angular.forEach($scope.users, function(item) {
$scope.checkboxes.items[item._id] = $scope.checkboxes.checked;
$scope.selection.push(item._id);
});
}
So far I've been successful in creating a function that removes an element from ng-repeat and to toggle a form. I can't figure out how to edit a given element in that ng-repeat.
Ideally, I'd like to click on the element, and have the form show with the existing values already in the input. So that all the user needs to do is edit whichever fields desired, click submit and that newly updated item is then added back to the array where it originally was.
This is what I've come up with:
<div ng-app="testApp">
<div ng-controller="testCtrl as vm">
<form ng-show="vm.showEditForm">
<input type="text" />
<input type="text" />
<button ng-click="vm.update()">Submit</button>
</form>
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="item in vm.list">
<td>
{{item.name}}
</td>
<td>
{{item.desc}}
<span ng-click="vm.toggleEditForm()">E</span>
<span ng-click="vm.removeItem($index)">X</span>
</td>
</tr>
</table>
</div>
</div>
and:
angular
.module('testApp', [])
.controller('testCtrl', testCtrl)
.service('testSrvc', testSrvc);
function testCtrl(testSrvc) {
var vm = this;
vm.list = testSrvc.list;
vm.removeItem = function(idx) {
testSrvc.remove(idx);
}
vm.showEditForm = false;
vm.toggleEditForm = function() {
vm.showEditForm = !vm.showEditForm;
};
vm.update = function() {
// ???
}
}
function testSrvc() {
this.list = [
{
name: 'asdf',
desc: 'lorem ipsum dolor'
},
{
name: 'qwerty',
desc: 'lorem ipsum amet'
}
];
this.remove = function(itemIndex) {
this.list.splice(itemIndex, 1);
};
this.edit = function() {
this.list.splice() //???
}
}
You need to tell which item you want to edit. So it should be
<span ng-click="vm.edit(item)">E</span>
Then this function should store a copy of that item to edit in some variable:
vm.edit= function(item) {
vm.editedItem = angular.copy(item);
};
And the form should be bound to this item copy:
<input type="text" ng-model="vm.editedItem.name"/>
<input type="text" ng-model="vm.editedItem.desc"/>
Then the save method should find back the original item in the array (thanks to its ID or index), and copy the edited fields from vm.editedItem.
angular
.module('testApp', [])
.controller('testCtrl', testCtrl)
.service('testSrvc', testSrvc);
function testCtrl(testSrvc) {
var vm = this;
vm.list = testSrvc.list;
this.index1 = -1;
vm.removeItem = function(idx) {
testSrvc.remove(idx);
}
vm.showEditForm = false;
vm.toggleEditForm = function(item,index) {
this.show = true;
this.index1 = index;
};
vm.update = function(item,index) {
vm.list[index].name = item.name;
vm.list[index].desc = item.desc;
this.index1 = -1;
}
}
function testSrvc() {
this.show = false;
this.list = [
{
name: 'asdf',
desc: 'lorem ipsum dolor'
},
{
name: 'qwerty',
desc: 'lorem ipsum amet'
}
];
this.remove = function(itemIndex) {
this.list.splice(itemIndex, 1);
};
this.edit = function(index) {
this.show = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp">
<div ng-controller="testCtrl as vm">
<form ng-show="vm.showEditForm">
</form>
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="item in vm.list" >
<td>
{{item.name}}
</td>
<td>
{{item.desc}}
<span ng-click="vm.toggleEditForm(item,$index)">E</span>
<input ng-show="vm.index1 == $index" type="text" ng-model="item.name" />
<input ng-show="vm.index1 == $index" type="text" ng-model="item.desc" />
<button ng-show="vm.index1 == $index" ng-click="vm.update(item,$index)">Submit</button>
<span ng-click="vm.removeItem($index)">X</span>
</td>
</tr>
</table>
</div>
</div>